Opencv 2
Opencv 2
Opencv 2
OPENCV2 html2pdf
document’s translation
C++ and C original document
Flavio Bernardotti
2010
HTTP://WWW.BERNARDOTTI.IT/PORTAL
A translation of original html file
http://opencv.willowgarage.com/documentation/cpp/index.html
1. (PROJECTS & SOURCE) : DOWN. DIVSHARE (5Gb) - DOWN. ESNIPS (5GB) - DOWN SKYDRIVE (25Gb)
2. (PDF & DOCS) PDF ISSUU ONLINE - PDF SCRIBD ONLINE - PDF DOCSTOC ONLINE
OpenCV Installation Guide
Overview:
• If you want the latest 2.0 release, get it here for Linux or Windows
• If you want the latest code, get it from our from out SVN server by:
o svn co https://code.ros.org/svn/opencv/trunk/opencv
• Mac users can read some details below, but mainly see how to install on Mac OS X.
• If you need detailed help, for Linux and some for Windows, read below:
Prerequisites
Common Prerequisites
• pkg-config. It is used at the configuration stage and also simplifies the further use of OpenCV itself.
• (Optional) gtk+ 2.x and the related packages (glib, gthread etc.).
o This is the GUI toolkit of choice for highgui on OSes other than Windows and MacOSX.
• (Optional) libjpeg, libtiff, libjasper, libpng and zlib. Install any of those with the associated
o development packages (libjpeg-dev etc. on Debian/Ubuntu) to be able to read/write the
corresponding image formats.
• (Optional) ffmpeg, libgstreamer, libxine, unicap, libdc1394 2.x (or libdc1394 1.x +
libraw1394).
o You should have some/all of these packages installed (together with associated
development packages) to add video capturing, video decoding and video encoding
capabilities to highgui. The output of the cmake will show you, which of the
packages have been detected and will be used in highgui. (Unable full video support
with FFMPEG). For example, on Ubuntu 8.10 all the necessary ffmpeg files can be
installed using the following command:
sudo apt-get install libavformat-dev libswscale-dev
• (Optional) Octave 2.9 or later, together with SWIG 1.3.36 or later, in order to build Octave
wrappers.
Extra Prerequisities (MacOSX)
• Xcode 3.1 or later. It does not only include the required C++ compiler, but also Quicktime
and Carbon frameworks that make highgui on MacOSX functional. Besides, CMake can
generate Xcode projects by the command "ccmake -G Xcode", so you can build OpenCV
conveniently from within the IDE. Additional information can be found on the
Mac_OS_X_OpenCV_Port page.
For example, if you downloaded the project to ~/projects/opencv, you can do the
following:
that will generate makefiles for the Release configuration and will put them in
~/projects/opencv/release directory.
Another example for Windows users (assuming the .exe extracted files to
C:\OpenCV2.0\)
cd C:\OpenCV2.0 # the directory containing INSTALL,
CMakeLists.txt etc.
mkdir release
cd release
cmake -D:CMAKE_BUILD_TYPE=RELEASE C:\OpenCV2.0
Note that the use of the colon after the -D is required on Windows Vista
(include if cmake is giving errors on other Windows distro's as well). If you
are using MS Visual Studio cmake exits with an error message "error
PRJ0003: Error spawning 'cmd.exe', make sure that you have the correct
VC++ Executable Directories set (see here).
3. Using IPP. If you have IPP installed on your machine and want to build OpenCV with IPP
support, check if IPP is turned on in CMake configuration options and if it was detected.
First, look at the CMake output. If it prints
o USE IPP: NO
o It means that IPP was not turned on or it was not detected. In this case turn it on
(USE_IPP=ON) and pass the correct path to IPP shared libraries (IPP_PATH=<...>),
like in the example below. While OpenCV currently uses static IPP libraries, it
derives their path from the supplied path to the shared/dynamic IPP libraries.
o If there are multiple IPP versions installed on the machine (not necessarily all of them are in
the system path) and you want to use the particular one, different from what CMake has
found, just specify the correct IPP_PATH.
4.
. If you generated project files for VisualStudio, Xcode, Eclipse etc., run the
respective IDE, open the OpenCV top-level project/solution/workspace etc. and
build it.
a. If you generated makefiles, then enter the created temporary directory and run
make/nmake utility. Then you can optionally run "sudo make install" (Linux, MacOSX).
5. If you did not run "make install", you should let your system know where to find the generated
libraries.
. In Windows you should add <cmake_binary_dir>/bin/debug and
<cmake_binary_dir>/bin/release
to the system path (My Computer--[Right button click]-->Properties-
>Advanced->Environment Variables->Path).
a. In Linux you should add <cmake_binary_dir>/lib[/debug|/release] to /etc/ld.so.conf
or to LD_LIBRARY_PATH, e.g.:
export
LD_LIBRARY_PATH=~/projects/opencv/release/lib:$LD_LIBRARY_PATH
sudo ldconfig
b. In MacOSX you should add <cmake_binary_dir>/lib[/debug|/release] to
DYLD_LIBRARY_PATH.
6. Note that the step is not needed to run OpenCV samples, because:
. on Windows both OpenCV DLLs and the samples are placed into the same directory
a. on Linux/MacOSX CMake embeds the correct library paths into the executables
Testing OpenCV
• You may turn on "BUILD_EXAMPLES" in CMake GUI or run cmake with "-D BUILD_EXAMPLES=ON"
option, then it will include short demo samples to the build. Note that some of them need image
files from the original source directory, you may just copy them to the bin directory.
• As long as you build Python/Octave wrappers and installed them, you can just enter
opencv/samples/swig_python or opencv/samples/octave and run the samples, e.g.
o python delaunay.py
• If you use CMake, you can write your own CMakeLists.txt script and use the provided
FindOpenCV.cmake file there,
o just like you would use FindJPEG.cmake etc. Please, refer to CMake documentation.
• You can add opencv include, lib and bin subdirectory to your IDE settings.
• For hand-written Makefiles you can specify the necessary paths and options manually, e.g.:
o g++ -o my_example my_example.cpp -
I<opencv_source_dir>/include[/opencv] \
o -L<cmake_binary_dir>/lib -lcxcore -lcv -lcvaux -lhighgui -
lml
• Finally, you can use pkg-config and the provided opencv.pc.
1. Make sure that opencv.pc is found by pkg-config:
2. pkg-config opencv --libs # should print something like -lcxcore
-lcv ...
3. You can now use it in your Makefiles or build scripts, e.g.:
• If you get compile errors to do with __exchange_and_add it is due to the wrong definition
of CV_XADD. It can be fixed by:
1. Open cxoperations.hpp (found in <Open CV base dir>\include\opencv)
2. Find this section (lines 67-68 in 2.0):
3. #else
4. #include <bits/atomicity.h>
#if __GNUC__ >= 4
The output matrix will have the same size and the same type as the input one (except for the
last case, where C will be depth=CV_8U).
absdiff¶
void absdiff(const Mat& src1, const Mat& src2, Mat& dst)
void absdiff(const Mat& src1, const Scalar& sc, Mat& dst)
void absdiff(const MatND& src1, const MatND& src2, MatND& dst)
void absdiff(const MatND& src1, const Scalar& sc, MatND& dst)
Computes per-element absolute difference between 2 arrays or between array and a scalar.
add¶
void add(const Mat& src1, const Mat& src2, Mat& dst)
void add(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask)
void add(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void add(const MatND& src1, const MatND& src2, MatND& dst)
void add(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask)
void add(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND())
The first function in the above list can be replaced with matrix expressions:
The functions addWeighted calculate the weighted sum of two arrays as follows:
cv::bitwise_and¶
Calculates per-element bit-wise conjunction of two arrays and an array and a scalar.
void bitwise_and(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat())¶
void bitwise_and(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void bitwise_and(const MatND& src1, const MatND& src2, MatND& dst, const MatND&
mask=MatND())
void bitwise_and(const MatND& src1, const Scalar& sc, MatND& dst, const MatND&
mask=MatND())
• of two arrays
cv::bitwise_not¶
Inverts every bit of array
void bitwise_not(const Mat& src, Mat& dst)¶
void bitwise_not(const MatND& src, MatND& dst)
The functions bitwise_not compute per-element bit-wise inversion of the source array:
In the case of floating-point source array its machine-specific bit representation (usually
IEEE754-compliant) is used for the operation. in the case of multi-channel arrays each
channel is processed independently.
cv::bitwise_or¶
Calculates per-element bit-wise disjunction of two arrays and an array and a scalar.
void bitwise_or(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat())¶
void bitwise_or(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void bitwise_or(const MatND& src1, const MatND& src2, MatND& dst, const MatND&
mask=MatND())
void bitwise_or(const MatND& src1, const Scalar& sc, MatND& dst, const MatND&
mask=MatND())
• of two arrays
cv::bitwise_xor¶
Calculates per-element bit-wise “exclusive or” operation on two arrays and an array and a scalar.
void bitwise_xor(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat())¶
void bitwise_xor(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void bitwise_xor(const MatND& src1, const MatND& src2, MatND& dst, const MatND&
mask=MatND())
void bitwise_xor(const MatND& src1, const Scalar& sc, MatND& dst, const MatND&
mask=MatND())
The functions bitwise_xor compute per-element bit-wise logical “exclusive or” operation
• on two arrays
calcCovarMatrix¶
void calcCovarMatrix(const Mat* samples, int nsamples, Mat& covar, Mat& mean, int flags, int
ctype=CV_64F)¶
void calcCovarMatrix(const Mat& samples, Mat& covar, Mat& mean, int flags, int
ctype=CV_64F)
, that is, covar will be a square matrix of the same size as the total number of elements in each
input vector. One and only one of CV_COVAR_SCRAMBLED and CV_COVAR_NORMAL must be specified
The functions calcCovarMatrix calculate the covariance matrix and, optionally, the mean vector
of the set of input vectors.
cartToPolar¶
void cartToPolar(const Mat& x, const Mat& y, Mat& magnitude, Mat& angle, bool
angleInDegrees=false)¶
The function cartToPolar calculates either the magnitude, angle, or both of every 2d vector
(x(I),y(I)):
The angles are calculated with accuracy. For the (0,0) point, the angle is set to 0.
checkRange¶
bool checkRange(const Mat& src, bool quiet=true, Point* pos=0, double minVal=-DBL_MAX,
double maxVal=DBL_MAX)¶
bool checkRange(const MatND& src, bool quiet=true, int* pos=0, double minVal=-DBL_MAX,
double maxVal=DBL_MAX)
The functions checkRange check that every array element is neither NaN nor . When
minVal < -DBL_MAX and maxVal < DBL_MAX, then the functions also check that each value
is between minVal and maxVal. in the case of multi-channel arrays each channel is
processed independently. If some values are out of range, position of the first outlier is
stored in pos (when ), and then the functions either return false (when
quiet=true) or throw an exception.
compare¶
void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop)
void compare(const Mat& src1, double value, Mat& dst, int cmpop)
void compare(const MatND& src1, const MatND& src2, MatND& dst, int cmpop)
void compare(const MatND& src1, double value, MatND& dst, int cmpop)
The functions compare compare each element of src1 with the corresponding element of
src2 or with real scalar value. When the comparison result is true, the corresponding
element of destination array is set to 255, otherwise it is set to 0:
The comparison operations can be replaced with the equivalent matrix expressions:
completeSymm¶
void completeSymm(Mat& mtx, bool lowerToUpper=false)¶
Copies the lower or the upper half of a square matrix to another half.
The function completeSymm copies the lower half of a square matrix to its another half; the
matrix diagonal remains unchanged:
• for if lowerToUpper=false
• for if lowerToUpper=true
See also: flip, transpose
convertScaleAbs¶
void convertScaleAbs(const Mat& src, Mat& dst, double alpha=1, double beta=0)¶
On each element of the input array the function convertScaleAbs performs 3 operations
sequentially: scaling, taking absolute value, conversion to unsigned 8-bit type:
in the case of multi-channel arrays the function processes each channel independently.
When the output is not 8-bit, the operation can be emulated by calling Mat::convertTo
method (or by using matrix expressions) and then by computing absolute value of the result,
for example:
Mat_<float> A(30,30);
randu(A, Scalar(-100), Scalar(100));
Mat_<float> B = A*5 + 3;
B = abs(B);
// Mat_<float> B = abs(A*5+3) will also do the job,
// but it will allocate a temporary matrix
countNonZero¶
int countNonZero(const Mat& mtx)¶
int countNonZero(const MatND& mtx)
The function cubeRoot computes . Negative arguments are handled correctly, NaN
and are not handled. The accuracy approaches the maximum possible accuracy for
single-precision data.
cvarrToMat¶
Mat cvarrToMat(const CvArr* src, bool copyData=false, bool allowND=true, int coiMode=0)¶
The parameter specifies how the IplImage COI (when set) is handled.
The function cvarrToMat() converts CvMat, IplImage or CvMatND header to Mat header,
and optionally duplicates the underlying data. The constructed header is returned by the
function.
When copyData=false, the conversion is done really fast (in O(1) time) and the newly
created matrix header will have refcount=0, which means that no reference counting is
done for the matrix data, and user has to preserve the data until the new header is destructed.
Otherwise, when copyData=true, the new buffer will be allocated and managed as if you
created a new matrix from scratch and copy the data there. That is, cvarrToMat(src,
true) :math:`$sim $() cvarrToMat(src, false).clone()` (assuming that COI is not set).
The function provides uniform way of supporting CvArr paradigm in the code that is
migrated to use new-style data structures internally. The reverse transformation, from Mat to
CvMat or IplImage can be done by simple assignment:
The last parameter, coiMode, specifies how to react on an image with COI set: by default
it’s 0, and then the function reports an error when an image with COI comes in. And
coiMode=1 means that no error is signaled - user has to check COI presence and handle it
manually. The modern structures, such as Mat and MatND do not support COI natively. To
process individual channel of an new-style array, you will need either to organize loop over
the array (e.g. using matrix iterators) where the channel of interest will be processed, or
extract the COI using mixChannels (for new-style arrays) or extractImageCOI (for old-style
arrays), process this individual channel and insert it back to the destination array if need
(using mixChannel or insertImageCOI, respectively).
dct¶
void dct(const Mat& src, Mat& dst, int flags=0)
The function dct performs a forward or inverse discrete cosine transform (DCT) of a 1D or
2D floating-point array:
where
and , for .
The function chooses the mode of operation by looking at the flags and size of the input
array:
Also, the function’s performance depends very much, and not monotonically, on the array
size, see getOptimalDFTSize. In the current implementation DCT of a vector of size N is
computed via DFT of a vector of size N/2, thus the optimal DCT size can be
computed as:
dft¶
void dft(const Mat& src, Mat& dst, int flags=0, int nonzeroRows=0)
param nonzeroRows:
When the parameter , the function assumes that only the first nonzeroRows rows of
the input array (DFT_INVERSE is not set) or only the first nonzeroRows of the output array
(DFT_INVERSE is set) contain non-zeros, thus the function can handle the rest of the rows
more efficiently and thus save some time. This technique is very useful for computing
array cross-correlation or convolution using DFT
where and
where
In the case of real (single-channel) data, the packed format called CCS (complex-conjugate-
symmetrical) that was borrowed from IPL and used to represent the result of a forward
Fourier transform or input for an inverse Fourier transform:
in the case of 1D transform of real vector, the output will look as the first row of the above
matrix.
So, the function chooses the operation mode depending on the flags and size of the input
array:
• if DFT_ROWS is set or the input array has single row or single column then the
function performs 1D forward or inverse transform (of each row of a matrix when
DFT_ROWS is set, otherwise it will be 2D transform.
• if input array is real and DFT_INVERSE is not set, the function does forward 1D or 2D
transform:
• when DFT_COMPLEX_OUTPUT is set then the output will be complex matrix of the
same size as input.
• otherwise the output will be a real matrix of the same size as input. in the case of 2D
transform it will use the packed format as shown above; in the case of single 1D
transform it will look as the first row of the above matrix; in the case of multiple 1D
transforms (when using DCT_ROWS flag) each row of the output matrix will look like
the first row of the above matrix.
• otherwise, if the input array is complex and either DFT_INVERSE or
DFT_REAL_OUTPUT are not set then the output will be a complex array of the same
size as input and the function will perform the forward or inverse 1D or 2D
transform of the whole input array or each row of the input array independently,
depending on the flags DFT_INVERSE and DFT_ROWS.
• otherwise, i.e. when DFT_INVERSE is set, the input array is real, or it is complex but
DFT_REAL_OUTPUT is set, the output will be a real array of the same size as input, and
the function will perform 1D or 2D inverse transformation of the whole input array
or each individual row, depending on the flags DFT_INVERSE and DFT_ROWS.
Unlike dct, the function supports arrays of arbitrary size, but only those arrays are processed
efficiently, which sizes can be factorized in a product of small prime numbers (2, 3 and 5 in
the current implementation). Such an efficient DFT size can be computed using
getOptimalDFTSize method.
Here is the sample on how to compute DFT-based convolution of two 2D real arrays:
All of the above improvements have been implemented in matchTemplate and filter2D,
therefore, by using them, you can get even better performance than with the above
theoretically optimal implementation (though, those two functions actually compute cross-
correlation, not convolution, so you will need to “flip” the kernel or the image around the
center using flip).
divide¶
void divide(const Mat& src1, const Mat& src2, Mat& dst, double scale=1)
void divide(double scale, const Mat& src2, Mat& dst)
void divide(const MatND& src1, const MatND& src2, MatND& dst, double scale=1)
void divide(double scale, const MatND& src2, MatND& dst)
The result will have the same type as src1. When src2(I)=0, dst(I)=0 too.
determinant¶
double determinant(const Mat& mtx)
Parameter: mtx – The input matrix; must have CV_32FC1 or CV_64FC1 type and square size
The function determinant computes and returns determinant of the specified matrix. For
small matrices (mtx.cols=mtx.rows<=3) the direct method is used; for larger matrices the
function uses LU factorization.
eigen¶
bool eigen(const Mat& src, Mat& eigenvalues, int lowindex=-1, int highindex=-1)
bool eigen(const Mat& src, Mat& eigenvalues, Mat& eigenvectors, int lowindex=-1, int
highindex=-1)
• src – The input matrix; must have CV_32FC1 or CV_64FC1 type, square
size and be symmetric:
• eigenvalues – The output vector of eigenvalues of the same type as
src; The eigenvalues are stored in the descending order.
• eigenvectors – The output matrix of eigenvectors; It will have the same
size and the same type as src; The eigenvectors are stored as
Parameters: subsequent matrix rows, in the same order as the corresponding
eigenvalues
• lowindex – Optional index of largest eigenvalue/-vector to calculate.
(See below.)
• highindex – Optional index of smallest eigenvalue/-vector to calculate.
(See below.)
If either low- or highindex is supplied the other is required, too. Indexing is 0-based.
Example: To calculate the largest eigenvector/-value set lowindex = highindex = 0. For
legacy reasons this function always returns a square matrix the same size as the source
matrix with eigenvectors and a vector the length of the source matrix with eigenvalues. The
selected eigenvectors/-values are always in the first highindex - lowindex + 1 rows.
exp¶
void exp(const Mat& src, Mat& dst)
void exp(const MatND& src, MatND& dst)
The function exp calculates the exponent of every element of the input array:
The maximum relative error is about for single-precision and less than for
double-precision. Currently, the function converts denormalized values to zeros on output.
Special values (NaN, ) are not handled.
extractImageCOI¶
void extractImageCOI(const CvArr* src, Mat& dst, int coi=-1)¶
The function extractImageCOI is used to extract image COI from an old-style array and
put the result to the new-style C++ matrix. As usual, the destination matrix is reallocated
using Mat::create if needed.
fastAtan2¶
float fastAtan2(float y, float x)¶
The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is
measured in degrees and varies from to . The accuracy is about .
flip¶
void flip(const Mat& src, Mat& dst, int flipCode)
The function flip flips the array in one of three different ways (row and column indices are
0-based):
gemm¶
void gemm(const Mat& src1, const Mat& src2, double alpha, const Mat& src3, double beta, Mat&
dst, int flags=0)
Operation flags:
o GEMM_1_T - transpose src1
o GEMM_2_T - transpose src2
o GEMM_3_T - transpose src3
The function performs generalized matrix multiplication and similar to the corresponding
functions *gemm in BLAS level 3. For example, gemm(src1, src2, alpha, src3, beta,
dst, GEMM_1_T + GEMM_3_T) corresponds to
The function can be replaced with a matrix expression, e.g. the above call can be replaced
with:
getConvertElem¶
ConvertData getConvertElem(int fromType, int toType)¶
ConvertScaleData getConvertScaleElem(int fromType, int toType)¶
typedef void (*ConvertData)(const void* from, void* to, int cn)¶
typedef void (*ConvertScaleData)(const void* from, void* to, int cn, double alpha, double
beta)¶
getOptimalDFTSize¶
int getOptimalDFTSize(int vecsize)¶
DFT performance is not a monotonic function of a vector size, therefore, when you compute
convolution of two arrays or do a spectral analysis of array, it usually makes sense to pad the
input data with zeros to get a bit larger array that can be transformed much faster than the
original one. Arrays, which size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to
process, though, the arrays, which size is a product of 2’s, 3’s and 5’s (e.g. 300 =
5*5*3*2*2), are also processed quite efficiently.
The function getOptimalDFTSize returns the minimum number N that is greater than or
equal to vecsize, such that the DFT of a vector of size N can be computed efficiently. In the
current implementation , for some , , .
The function returns a negative number if vecsize is too large (very close to INT_MAX).
While the function cannot be used directly to estimate the optimal vector size for DCT
transform (since the current DCT implementation supports only even-size vectors), it can be
easily computed as getOptimalDFTSize((vecsize+1)/2)*2.
idct¶
void idct(const Mat& src, Mat& dst, int flags=0)
idft¶
void idft(const Mat& src, Mat& dst, int flags=0, int outputRows=0)
inRange¶
void inRange(const Mat& src, const Mat& lowerb, const Mat& upperb, Mat& dst)¶
void inRange(const Mat& src, const Scalar& lowerb, const Scalar& upperb, Mat& dst)
void inRange(const MatND& src, const MatND& lowerb, const MatND& upperb, MatND& dst)
void inRange(const MatND& src, const Scalar& lowerb, const Scalar& upperb, MatND& dst)
Checks if array elements lie between the elements of two other arrays.
The functions inRange do the range check for every element of the input array:
for two-channel arrays and so forth. dst``(I) is set to 255 (all ``1-bits) if ``src``(I)
is within the specified range and 0 otherwise.
invert¶
double invert(const Mat& src, Mat& dst, int method=DECOMP_LU)
The function invert inverts matrix src and stores the result in dst. When the matrix src is
singular or non-square, the function computes the pseudo-inverse matrix, i.e. the matrix dst,
such that is minimal.
In the case of DECOMP_LU method, the function returns the src determinant (src must be
square). If it is 0, the matrix is not inverted and dst is filled with zeros.
In the case of DECOMP_SVD method, the function returns the inversed condition number of
src (the ratio of the smallest singular value to the largest singular value) and 0 if src is
singular. The SVD method calculates a pseudo-inverse matrix if src is singular.
Similarly to DECOMP_LU, the method DECOMP_CHOLESKY works only with non-singular square
matrices. In this case the function stores the inverted matrix in dst and returns non-zero,
otherwise it returns 0.
log¶
void log(const Mat& src, Mat& dst)
void log(const MatND& src, MatND& dst)
The function log calculates the natural logarithm of the absolute value of every element of
the input array:
Where C is a large negative number (about -700 in the current implementation). The
maximum relative error is about for single-precision input and less than for
double-precision input. Special values (NaN, ) are not handled.
LUT¶
void LUT(const Mat& src, const Mat& lut, Mat& dst)¶
The function cvLUT() fills the destination array with values from the look-up table. Indices
of the entries are taken from the source array. That is, the function processes each element of
src as follows:
where
magnitude¶
void magnitude(const Mat& x, const Mat& y, Mat& magnitude)
The function magnitude calculates magnitude of 2D vectors formed from the corresponding
elements of x and y arrays:
See also: cartToPolar, polarToCart, phase, sqrt
Mahalanobis¶
double Mahalanobis(const Mat& vec1, const Mat& vec2, const Mat& icovar)¶
The function cvMahalonobis() calculates and returns the weighted distance between two
vectors:
The covariance matrix may be calculated using the calcCovarMatrix function and then
inverted using the invert function (preferably using DECOMP_SVD method, as the most
accurate).
max¶
Mat_Expr<...> max(const Mat& src1, const Mat& src2)
Mat_Expr<...> max(const Mat& src1, double value)
Mat_Expr<...> max(double value, const Mat& src1)
void max(const Mat& src1, const Mat& src2, Mat& dst)
void max(const Mat& src1, double value, Mat& dst)
void max(const MatND& src1, const MatND& src2, MatND& dst)
void max(const MatND& src1, double value, MatND& dst)
In the second variant, when the source array is multi-channel, each channel is compared
with value independently.
The first 3 variants of the function listed above are actually a part of Matrix Expressions,
they return the expression object that can be further transformed, or assigned to a matrix, or
passed to a function etc.
mean¶
Scalar mean(const Mat& mtx)
Scalar mean(const Mat& mtx, const Mat& mask)
Scalar mean(const MatND& mtx)
Scalar mean(const MatND& mtx, const MatND& mask)
• mtx – The source array; it should have 1 to 4 channels (so that the
result can be stored in Scalar)
Parameters:
• mask – The optional operation mask
The functions mean compute mean value M of array elements, independently for each
channel, and return it:
When all the mask elements are 0’s, the functions return Scalar::all(0).
meanStdDev¶
void meanStdDev(const Mat& mtx, Scalar& mean, Scalar& stddev, const Mat& mask=Mat())¶
void meanStdDev(const MatND& mtx, Scalar& mean, Scalar& stddev, const MatND&
mask=MatND())
• mtx – The source array; it should have 1 to 4 channels (so that the
Parameters:
results can be stored in Scalar‘s)
• mean – The output parameter: computed mean value
• stddev – The output parameter: computed standard deviation
• mask – The optional operation mask
The functions meanStdDev compute the mean and the standard deviation M of array
elements, independently for each channel, and return it via the output parameters:
When all the mask elements are 0’s, the functions return mean=stddev=Scalar::all(0).
Note that the computed standard deviation is only the diagonal of the complete normalized
covariance matrix. If the full matrix is needed, you can reshape the multi-channel array
to the single-channel array (only possible when the
matrix is continuous) and then pass the matrix to calcCovarMatrix.
merge¶
void merge(const Mat* mv, size_t count, Mat& dst)
void merge(const vector<Mat>& mv, Mat& dst)
void merge(const MatND* mv, size_t count, MatND& dst)
void merge(const vector<MatND>& mv, MatND& dst)
The functions merge merge several single-channel arrays (or rather interleave their
elements) to make a single multi-channel array.
The function split does the reverse operation and if you need to merge several multi-channel
images or shuffle channels in some other advanced way, use mixChannels
See also: mixChannels, split, reshape
min¶
Mat_Expr<...> min(const Mat& src1, const Mat& src2)
Mat_Expr<...> min(const Mat& src1, double value)
Mat_Expr<...> min(double value, const Mat& src1)
void min(const Mat& src1, const Mat& src2, Mat& dst)
void min(const Mat& src1, double value, Mat& dst)
void min(const MatND& src1, const MatND& src2, MatND& dst)
void min(const MatND& src1, double value, MatND& dst)
In the second variant, when the source array is multi-channel, each channel is compared
with value independently.
The first 3 variants of the function listed above are actually a part of Matrix Expressions,
they return the expression object that can be further transformed, or assigned to a matrix, or
passed to a function etc.
minMaxLoc¶
void minMaxLoc(const Mat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point*
maxLoc=0, const Mat& mask=Mat())¶
void minMaxLoc(const MatND& src, double* minVal, double* maxVal, int* minIdx=0, int*
maxIdx=0, const MatND& mask=MatND())
void minMaxLoc(const SparseMat& src, double* minVal, double* maxVal, int* minIdx=0, int*
maxIdx=0)
The functions ninMaxLoc find minimum and maximum element values and their positions.
The extremums are searched across the whole array, or, if mask is not an empty array, in the
specified array region.
The functions do not work with multi-channel arrays. If you need to find minimum or
maximum elements across all the channels, use reshape first to reinterpret the array as
single-channel. Or you may extract the particular channel using extractImageCOI or
mixChannels or split.
in the case of a sparse matrix the minimum is found among non-zero elements only.
See also: max, min, compare, inRange, extractImageCOI, mixChannels, split, reshape.
mixChannels¶
void mixChannels(const Mat* srcv, int nsrc, Mat* dstv, int ndst, const int* fromTo, size_t npairs)¶
void mixChannels(const MatND* srcv, int nsrc, MatND* dstv, int ndst, const int* fromTo, size_t
npairs)
void mixChannels(const vector<Mat>& srcv, vector<Mat>& dstv, const int* fromTo, int npairs)
void mixChannels(const vector<MatND>& srcv, vector<MatND>& dstv, const int* fromTo, int
npairs)
Copies specified channels from input arrays to the specified channels of output arrays
• srcv – The input array or vector of matrices. All the matrices must have
the same size and the same depth
• nsrc – The number of elements in srcv
• dstv – The output array or vector of matrices. All the matrices must be
Parameters: allocated, their size and depth must be the same as in srcv[0]
• ndst – The number of elements in dstv
• fromTo – The array of index pairs, specifying which channels are
copied and where. fromTo[k*2] is the 0-based index of the input
channel in srcv and fromTo[k*2+1] is the index of the output channel
in dstv. Here the continuous channel numbering is used, that is, the
first input image channels are indexed from 0 to
srcv[0].channels()-1, the second input image channels are indexed
from srcv[0].channels() to srcv[0].channels() +
srcv[1].channels()-1 etc., and the same scheme is used for the
output image channels. As a special case, when fromTo[k*2] is
negative, the corresponding output channel is filled with zero.
``npairs``bgroup({The number of pairs. In the latter case the parameter
is not passed explicitly, but computed as texttt{srcv.size()}
(=texttt{dstv.size()})})
The functions mixChannels provide an advanced mechanism for shuffling image channels.
split and merge and some forms of cvtColor are partial cases of mixChannels.
As an example, this code splits a 4-channel RGBA image into a 3-channel BGR (i.e. with R
and B channels swapped) and separate alpha channel image:
Note that, unlike many other new-style C++ functions in OpenCV (see the introduction
section and Mat::create), mixChannels requires the destination arrays be pre-allocated
before calling the function.
mulSpectrums¶
void mulSpectrums(const Mat& src1, const Mat& src2, Mat& dst, int flags, bool conj=false)¶
The function, together with dft and idft, may be used to calculate convolution (pass
conj=false) or correlation (pass conj=false) of two arrays rapidly. When the arrays are
complex, they are simply multiplied (per-element) with optional conjugation of the second
array elements. When the arrays are real, they assumed to be CCS-packed (see dft for
details).
multiply¶
void multiply(const Mat& src1, const Mat& src2, Mat& dst, double scale=1)
void multiply(const MatND& src1, const MatND& src2, MatND& dst, double scale=1)
There is also Matrix Expressions-friendly variant of the first function, see Mat::mul.
If you are looking for a matrix product, not per-element product, see gemm.
See also: add, substract, divide, Matrix Expressions, scaleAdd, addWeighted, accumulate,
accumulateProduct, accumulateSquare, Mat::convertTo
mulTransposed¶
void mulTransposed(const Mat& src, Mat& dst, bool aTa, const Mat& delta=Mat(), double
scale=1, int rtype=-1)¶
The function mulTransposed calculates the product of src and its transposition:
if aTa=true, and
otherwise. The function is used to compute covariance matrix and with zero delta can be
used as a faster substitute for general matrix product when .
norm¶
double norm(const Mat& src1, int normType=NORM_L2)
double norm(const Mat& src1, const Mat& src2, int normType=NORM_L2)
double norm(const Mat& src1, int normType, const Mat& mask)
double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask)
double norm(const MatND& src1, int normType=NORM_L2, const MatND& mask=MatND())
double norm(const MatND& src1, const MatND& src2, int normType=NORM_L2, const MatND&
mask=MatND())
double norm(const SparseMat& src, int normType)
Calculates absolute array norm, absolute difference norm, or relative difference norm.
The functions norm calculate the absolute norm of src1 (when there is no src2):
or an absolute or relative difference norm if src2 is there:
or
When there is mask parameter, and it is not empty (then it should have type CV_8U and the
same size as src1), the norm is computed only over the specified by the mask region.
A multiple-channel source arrays are treated as a single-channel, that is, the results for all
channels are combined.
normalize¶
void normalize(const Mat& src, Mat& dst, double alpha=1, double beta=0, int
normType=NORM_L2, int rtype=-1, const Mat& mask=Mat())
void normalize(const MatND& src, MatND& dst, double alpha=1, double beta=0, int
normType=NORM_L2, int rtype=-1, const MatND& mask=MatND())
void normalize(const SparseMat& src, SparseMat& dst, double alpha, int normType)
The optional mask specifies the sub-array to be normalize, that is, the norm or min-n-max
are computed over the sub-array and then this sub-array is modified to be normalized. If you
want to only use the mask to compute the norm or min-max, but modify the whole array,
you can use norm and
Mat::convertScale/MatND::convertScale/crossbgroup({SparseMat::convertScale})
separately.
in the case of sparse matrices, only the non-zero values are analyzed and transformed.
Because of this, the range transformation for sparse matrices is not allowed, since it can shift
the zero level.
PCA¶
Class for Principal Component Analysis
class PCA
{
public:
// default constructor
PCA();newline
// computes PCA for a set of vectors stored as data rows or columns.
PCA(const Mat& data, const Mat& mean, int flags, int
maxComponents=0);newline
// computes PCA for a set of vectors stored as data rows or columns
PCA& operator()(const Mat& data, const Mat& mean, int flags, int
maxComponents=0);newline
// projects vector into the principal components space
Mat project(const Mat& vec) const;newline
void project(const Mat& vec, Mat& result) const;newline
// reconstructs the vector from its PC projection
Mat backProject(const Mat& vec) const;newline
void backProject(const Mat& vec, Mat& result) const;newline
The following sample is the function that takes two matrices. The first one stores the set of vectors
(a row per vector) that is used to compute PCA, the second one stores another “test” set of vectors
(a row per vector) that are first compressed with PCA, then reconstructed back and then the
reconstruction error norm is computed and printed for each vector.
Mat reconstructed;
for( int i = 0; i < testset.rows; i++ )
{
Mat vec = testset.row(i), coeffs = compressed.row(i);
// compress the vector, the result will be stored
// in the i-th row of the output matrix
pca.project(vec, coeffs);
// and then reconstruct it
pca.backProject(coeffs, reconstructed);
// and measure the error
printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
}
return pca;
}
perspectiveTransform¶
void perspectiveTransform(const Mat& src, Mat& dst, const Mat& mtx)¶
where
and
Note that the function transforms a sparse set of 2D or 3D vectors. If you want to transform
an image using perspective transformation, use warpPerspective. If you have an inverse
task, i.e. want to compute the most probable perspective transformation out of several pairs
of corresponding points, you can use getPerspectiveTransform or findHomography.
phase¶
void phase(const Mat& x, const Mat& y, Mat& angle, bool angleInDegrees=false)
See also:
polarToCart¶
void polarToCart(const Mat& magnitude, const Mat& angle, Mat& x, Mat& y, bool
angleInDegrees=false)¶
pow¶
void pow(const Mat& src, double p, Mat& dst)
void pow(const MatND& src, double p, MatND& dst)
That is, for a non-integer power exponent the absolute values of input array elements are
used. However, it is possible to get true values for negative values using some extra
operations, as the following example, computing the 5th root of array src, shows:
For some values of p, such as integer values, 0.5, and -0.5, specialized faster algorithms are
used.
randu¶
template<typename _Tp> _Tp randu()
void randu(Mat& mtx, const Scalar& low, const Scalar& high)
• mtx – The output array of random numbers. The array must be pre-
allocated and have 1 to 4 channels
Parameters: • low – The inclusive lower boundary of the generated random numbers
• high – The exclusive upper boundary of the generated random numbers
The template functions randu generate and return the next uniformly-distributed random
value of the specified type. randu<int>() is equivalent to (int)theRNG(); etc. See RNG
description.
The second non-template variant of the function fills the matrix mtx with uniformly-
distributed random numbers from the specified range:
randn¶
void randn(Mat& mtx, const Scalar& mean, const Scalar& stddev)
• mtx – The output array of random numbers. The array must be pre-
allocated and have 1 to 4 channels
• mean – The mean value (expectation) of the generated random
Parameters:
numbers
• stddev – The standard deviation of the generated random numbers
The function randn fills the matrix mtx with normally distributed random numbers with the
specified mean and standard deviation. [cppfunc.saturatecast]bgroup({saturate_ cast}) is
applied to the generated numbers (i.e. the values are clipped)
randShuffle¶
void randShuffle(Mat& mtx, double iterFactor=1., RNG* rng=0)¶
The function randShuffle shuffles the specified 1D array by randomly choosing pairs of
elements and swapping them. The number of such swap operations will be
mtx.rows*mtx.cols*iterFactor
reduce¶
void reduce(const Mat& mtx, Mat& vec, int dim, int reduceOp, int dtype=-1)
The function reduce reduces matrix to a vector by treating the matrix rows/columns as a set
of 1D vectors and performing the specified operation on the vectors until a single
row/column is obtained. For example, the function can be used to compute horizontal and
vertical projections of an raster image. In the case of CV_REDUCE_SUM and CV_REDUCE_AVG
the output may have a larger element bit-depth to preserve accuracy. And multi-channel
arrays are also supported in these two reduction modes.
repeat¶
void repeat(const Mat& src, int ny, int nx, Mat& dst)
Mat repeat(const Mat& src, int ny, int nx)
Fill the destination array with repeated copies of the source array.
The functions repeat duplicate the source array one or more times along each of the two
axes:
The second variant of the function is more convenient to use with Matrix Expressions
saturate_cast¶
Template function for accurate conversion from one primitive type to another
template<typename _Tp> inline _Tp saturate_cast(unsigned char v)¶
template<typename _Tp> inline _Tp saturate_cast(signed char v)
template<typename _Tp> inline _Tp saturate_cast(unsigned short v)
template<typename _Tp> inline _Tp saturate_cast(signed short v)
template<typename _Tp> inline _Tp saturate_cast(int v)
template<typename _Tp> inline _Tp saturate_cast(unsigned int v)
template<typename _Tp> inline _Tp saturate_cast(float v)
template<typename _Tp> inline _Tp saturate_cast(double v)
The functions saturate_cast resembles the standard C++ cast operations, such as
static_cast<T>() etc. They perform an efficient and accurate conversion from one
primitive type to another, see the introduction. “saturate” in the name means that when the
input value v is out of range of the target type, the result will not be formed just by taking
low bits of the input, but instead the value will be clipped. For example:
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 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 most simple or complex image processing functions in OpenCV.
scaleAdd¶
void scaleAdd(const Mat& src1, double scale, const Mat& src2, Mat& dst)¶
void scaleAdd(const MatND& src1, double scale, const MatND& src2, MatND& dst)
The function cvScaleAdd() is one of the classical primitive linear algebra operations,
known as DAXPY or SAXPY in
bgroup({http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms})bgroup({BLAS
}). It calculates the sum of a scaled array and another array:
The function can also be emulated with a matrix expression, for example:
setIdentity¶
void setIdentity(Mat& dst, const Scalar& value=Scalar(1))¶
The function can also be emulated using the matrix initializers and the matrix expressions:
solve¶
bool solve(const Mat& src1, const Mat& src2, Mat& dst, int flags=DECOMP_LU)
The function solve solves a linear system or least-squares problem (the latter is possible
with SVD or QR methods, or by specifying the flag DECOMP_NORMAL):
Note that if you want to find unity-norm solution of an under-defined singular system
, the function solve will not do the work. Use SVD::solveZ instead.
solveCubic¶
void solveCubic(const Mat& coeffs, Mat& roots)¶
solvePoly¶
void solvePoly(const Mat& coeffs, Mat& roots, int maxIters=20, int fig=100)¶
The function solvePoly finds real and complex roots of a polynomial equation:
sort¶
void sort(const Mat& src, Mat& dst, int flags)
The function sort sorts each matrix row or each matrix column in ascending or descending
order. If you want to sort matrix rows or columns lexicographically, you can use STL
std::sort generic function with the proper comparison predicate.
See also: sortIdx, randShuffle
sortIdx¶
void sortIdx(const Mat& src, Mat& dst, int flags)¶
The function sortIdx sorts each matrix row or each matrix column in ascending or
descending order. Instead of reordering the elements themselves, it stores the indices of
sorted elements in the destination array. For example:
Mat A = Mat::eye(3,3,CV_32F), B;
sortIdx(A, B, CV_SORT_EVERY_ROW + CV_SORT_ASCENDING);
// B will probably contain
// (because of equal elements in A some permutations are possible):
// [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
split¶
void split(const Mat& mtx, Mat* mv)
void split(const Mat& mtx, vector<Mat>& mv)
void split(const MatND& mtx, MatND* mv)
void split(const MatND& mtx, vector<MatND>& mv)
The functions split split multi-channel array into separate single-channel arrays:
sqrt¶
void sqrt(const Mat& src, Mat& dst)
void sqrt(const MatND& src, MatND& dst)
The functions sqrt calculate square root of each source array element. in the case of multi-
channel arrays each channel is processed independently. The function accuracy is
approximately the same as of the built-in std::sqrt.
subtract¶
void subtract(const Mat& src1, const Mat& src2, Mat& dst)
void subtract(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask)
void subtract(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void subtract(const Scalar& sc, const Mat& src2, Mat& dst, const Mat& mask=Mat())
void subtract(const MatND& src1, const MatND& src2, MatND& dst)
void subtract(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask)
void subtract(const MatND& src1, const Scalar& sc, MatND& dst, const MatND&
mask=MatND())
void subtract(const Scalar& sc, const MatND& src2, MatND& dst, const MatND&
mask=MatND())
The first function in the above list can be replaced with matrix expressions:
SVD¶
Class for computing Singular Value Decomposition
class SVD
{
public:
enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 };newline
// default empty constructor
SVD();newline
// decomposes m into u, w and vt: m = u*w*vt;newline
// u and vt are orthogonal, w is diagonal
SVD( const Mat& m, int flags=0 );newline
// decomposes m into u, w and vt.
SVD& operator ()( const Mat& m, int flags=0 );newline
The class cvSVD() is used to compute Singular Value Decomposition of a floating-point matrix and
then use it to solve least-square problems, under-determined linear systems, invert matrices,
compute condition numbers etc. For a bit faster operation you can pass flags=SVD::MODIFY_A|...
to modify the decomposed matrix when it is not necessarily to preserve it. If you want to compute
condition number of a matrix or absolute value of its determinant - you do not need u and vt, so
you can pass flags=SVD::NO_UV|.... Another flag FULL_UV indicates that full-size u and vt must
be computed, which is not necessary most of the time.
sum¶
Scalar sum(const Mat& mtx)
Scalar sum(const MatND& mtx)
The functions sum calculate and return the sum of array elements, independently for each
channel.
theRNG¶
RNG& theRNG()¶
The function theRNG returns the default random number generator. For each thread there is
separate random number generator, so you can use the function safely in multi-thread
environments. If you just need to get a single random number using this generator or
initialize an array, you can use randu or randn instead. But if you are going to generate
many random numbers inside a loop, it will be much faster to use this function to retrieve
the generator and then use RNG::operator _Tp().
trace¶
Scalar trace(const Mat& mtx)
The function trace returns the sum of the diagonal elements of the matrix mtx.
transform¶
void transform(const Mat& src, Mat& dst, const Mat& mtx)
The function transform performs matrix transformation of every element of array src and
stores the results in dst:
(when mtx.cols=src.channels()), or
(when mtx.cols=src.channels()+1)
That is, every element of an N-channel array src is considered as N-element vector, which is
transformed using a or matrix mtx into an element of M-channel array dst.
transpose¶
void transpose(const Mat& src, Mat& dst)
Transposes a matrix
Note that no complex conjugation is done in the case of a complex matrix, it should be done
separately if needed.
Drawing Functions¶
Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can
be rendered with antialiasing (implemented only for 8-bit images for now). All the functions
include the parameter color that uses a rgb value (that may be constructed with CV_RGB or the
Scalar constructor) for color images and brightness for grayscale images. For color images the
order channel is normally Blue, Green, Red, this is what imshow, imread and imwrite expect , so if
you form a color using Scalar constructor, it should look like:
If you are using your own image rendering and I/O functions, you can use any channel ordering, the
drawing functions process each channel independently and do not depend on the channel order or
even on the color space used. The whole image can be converted from BGR to RGB or to a
different color space using cvtColor.
If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also,
many drawing functions can handle pixel coordinates specified with sub-pixel accuracy, that is, the
coordinates can be passed as fixed-point numbers, encoded as integers. The number of fractional
bits is specified by the shift parameter and the real point coordinates are calculated as
. This feature is especially effective wehn
rendering antialiased shapes.
Also, note that the functions do not support alpha-transparency - when the target image is 4-
channnel, then the color[3] is simply copied to the repainted pixels. Thus, if you want to paint semi-
transparent shapes, you can paint them in a separate buffer and then blend it with the main image.
circle¶
void circle(Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int
lineType=8, int shift=0)
Draws a circle
The function circle draws a simple or filled circle with a given center and radius.
clipLine¶
bool clipLine(Size imgSize, Point& pt1, Point& pt2)¶
bool clipLine(Rect imgRect, Point& pt1, Point& pt2)
The functions clipLine calculate a part of the line segment which is entirely within the
specified rectangle. They return false if the line segment is completely outside the rectangle
and true otherwise.
ellipse¶
void ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double
endAngle, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
void ellipse(Mat& img, const RotatedRect& box, const Scalar& color, int thickness=1, int
lineType=8)
The functions ellipse with less parameters draw an ellipse outline, a filled ellipse, an elliptic
arc or a filled ellipse sector. A piecewise-linear curve is used to approximate the elliptic arc
boundary. If you need more control of the ellipse rendering, you can retrieve the curve using
ellipse2Poly and then render it with polylines or fill it with fillPoly. If you use the first
variant of the function and want to draw the whole ellipse, not an arc, pass startAngle=0 and
endAngle=360. The picture below explains the meaning of the parameters.
ellipse2Poly¶
void ellipse2Poly(Point center, Size axes, int angle, int startAngle, int endAngle, int delta,
vector<Point>& pts)¶
The function ellipse2Poly computes the vertices of a polyline that approximates the
specified elliptic arc. It is used by ellipse.
fillConvexPoly¶
void fillConvexPoly(Mat& img, const Point* pts, int npts, const Scalar& color, int lineType=8,
int shift=0)¶
• img – Image
• pts – The polygon vertices
• npts – The number of polygon vertices
Parameters: • color – Polygon color
• lineType – Type of the polygon boundaries, see line description
• shift – The number of fractional bits in the vertex coordinates
The function fillConvexPoly draws a filled convex polygon. This function is much faster
than the function fillPoly and can fill not only convex polygons but any monotonic polygon
without self-intersections, i.e., a polygon whose contour intersects every horizontal line
(scan line) twice at the most (though, its top-most and/or the bottom edge could be
horizontal).
fillPoly¶
void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int
lineType=8, int shift=0, Point offset=Point())¶
• img – Image
• pts – Array of polygons, each represented as an array of points
• npts – The array of polygon vertex counters
• ncontours – The number of contours that bind the filled region
Parameters:
• color – Polygon color
• lineType – Type of the polygon boundaries, see line description
• shift – The number of fractional bits in the vertex coordinates
The function fillPoly fills an area bounded by several polygonal contours. The function can
fills complex areas, for example, areas with holes, contours with self-intersections (some of
thier parts), and so forth.
getTextSize¶
Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine)¶
The function getTextSize calculates and returns size of the box that contain the specified
text. That is, the following code will render some text, the tight box surrounding it and the
baseline:
int baseline=0;
Size textSize = getTextSize(text, fontFace,
fontScale, thickness, &baseline);
baseline += thickness;
line¶
void line(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int
shift=0)
The function line draws the line segment between pt1 and pt2 points in the image. The line
is clipped by the image boundaries. For non-antialiased lines with integer coordinates the 8-
connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with
rounding endings. Antialiased lines are drawn using Gaussian filtering. To specify the line
color, the user may use the macro CV_RGB(r, g, b).
LineIterator¶
Class for iterating pixels on a raster line
class LineIterator
{
public:
// creates iterators for the line connecting pt1 and pt2
// the line will be clipped on the image boundaries
// the line is 8-connected or 4-connected
// If leftToRight=true, then the iteration is always done
// from the left-most point to the right most,
// not to depend on the ordering of pt1 and pt2 parameters
LineIterator(const Mat& img, Point pt1, Point pt2,
int connectivity=8, bool leftToRight=false);newline
// returns pointer to the current line pixel
uchar* operator *();newline
// move the iterator to the next pixel
LineIterator& operator ++();newline
LineIterator operator ++(int);newline
The class LineIterator is used to get each pixel of a raster line. It can be treated as versatile
implementation of the Bresenham algorithm, where you can stop at each pixel and do some extra
processing, for example, grab pixel values along the line, or draw a line with some effect (e.g. with
XOR operation).
• img – Image
• pt1 – One of the rectangle’s vertices
• pt2 – Opposite to pt1 rectangle vertex
• color – Rectangle color or brightness (grayscale image)
• thickness – Thickness of lines that make up the rectangle. Negative
Parameters:
values, e.g. CV_FILLED, mean that the function has to draw a filled
rectangle.
• lineType – Type of the line, see line description
• shift – Number of fractional bits in the point coordinates
The function rectangle draws a rectangle outline or a filled rectangle, which two opposite
corners are pt1 and pt2.
polylines¶
void polylines(Mat& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const
Scalar& color, int thickness=1, int lineType=8, int shift=0)
putText¶
void putText(Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color,
int thickness=1, int lineType=8, bool bottomLeftOrigin=false)¶
Draws a text string
• FONT_HERSHEY_SCRIPT_COMPLEX - ,
• FONT_HERSHEY_ITALIC - t
The function putText draws a text string in the image. Symbols that can not be rendered
using the specified font are replaced question marks. See getTextSize for a text rendering
code example.
XML/YAML Persistence¶
FileStorage¶
The XML/YAML file storage class
class FileStorage
{
public:
enum { READ=0, WRITE=1, APPEND=2 };
enum { UNDEFINED=0, VALUE_EXPECTED=1, NAME_EXPECTED=2, INSIDE_MAP=4 };
// the default constructor
FileStorage();
// the constructor that opens the file for reading
// (flags=FileStorage::READ) or writing (flags=FileStorage::WRITE)
FileStorage(const string& filename, int flags);
// wraps the already opened CvFileStorage*
FileStorage(CvFileStorage* fs);
// the destructor; closes the file if needed
virtual ~FileStorage();
Ptr<CvFileStorage> fs;
string elname;
vector<char> structs;
int state;
};
FileNode¶
The XML/YAML file node class
void readRaw( const string& fmt, uchar* vec, size_t len ) const;
void* readObj() const;
FileNodeIterator¶
The XML/YAML file node iterator class
The function kmeans implements a k-means algorithm that finds the centers of
clusterCount clusters and groups the input samples around the clusters. On output,
contains a 0-based cluster index for the sample stored in the row of the
samples matrix.
after every attempt; the best (minimum) value is chosen and the corresponding labels and
the compactness value are returned by the function. Basically, the user can use only the core
of the function, set the number of attempts to 1, initialize labels each time using some
custom algorithm and pass them with
partition¶
template<typename _Tp, class _EqPredicate> int partition(const vector<_Tp>& vec,
vector<int>& labels, _EqPredicate predicate=_EqPredicate())
flann::Index¶
The FLANN nearest neighbor index class.
namespace flann
{
class Index
{
public:
Index(const Mat& features, const IndexParams& params);
flann::Index::Index¶
Index::Index(const Mat& features, const IndexParams& params)¶
Structure containing the index parameters. The type of index that will
be constructed depends on the type of this parameter. The possible
parameter types are:
flann::Index::knnSearch¶
void Index::knnSearch(const vector<float>& query, vector<int>& indices, vector<float>& dists,
int knn, const SearchParams& params)¶
Performs a K-nearest neighbor search for a given query point using the index.
Search parameters
struct SearchParams {
SearchParams(int checks = 32);
};
flann::Index::knnSearch¶
void Index::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const
SearchParams& params)
flann::Index::radiusSearch¶
int Index::radiusSearch(const vector<float>& query, vector<int>& indices, vector<float>&
dists, float radius, const SearchParams& params)¶
flann::Index::radiusSearch¶
int Index::radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const
SearchParams& params)
Performs a radius nearest neighbor search for multiple query points.
flann::Index::save¶
void Index::save(std::string filename)¶
flann::hierarchicalClustering¶
int hierarchicalClustering(const Mat& features, Mat& centers, const KMeansIndexParams&
params)¶
Clusters the given points by constructing a hierarchical k-means tree and choosing a cut in
the tree that minimizes the cluster’s variance.
The function returns the aligned pointer of the same type as the input pointer:
alignSize¶
size_t alignSize(size_t sz, int n)¶
The function returns the minimum number that is greater or equal to sz and is divisble by n:
allocate¶
template<typename _Tp> _Tp* allocate(size_t n)
The generic function allocate allocates buffer for the specified number of elements. For
each element the default constructor is called.
deallocate¶
template<typename _Tp> void deallocate(_Tp* ptr, size_t n)
The generic function deallocate deallocates the buffer allocated with allocate. The number
of elements must match the number passed to allocate.
CV_Assert¶
Checks a condition at runtime.
The macros CV_Assert and CV_DbgAssert evaluate the specified expression and if it is 0, the
macros raise an error (see 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¶
void error(const Exception& exc)
# define CV_Error( code, msg ) <...> # define CV_Error_( code, args ) <...>
The function and the helper macros CV_Error and CV_Error_ call the error handler.
Currently, the error handler prints the error code (exc.code), the context (exc.file,
exc.line and the error message exc.err to the standard error stream stderr. In Debug
configuration it then provokes memory access violation, so that the execution stack and all
the parameters can be analyzed in debugger. In Release configuration the exception exc is
thrown.
The macro CV_Error_ can be used to construct the error message on-fly to include some
dynamic information, for example:
Exception¶
The exception class passed to 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);newline
Exception(const Exception& exc);newline
Exception& operator = (const Exception& exc);newline
// the error code
int code;newline
// the error text message
string err;newline
// function name where the error happened
string func;newline
// the source file name where the error happened
string file;newline
// the source file line where the error happened
int line;
};
The class Exception encapsulates all or almost all the necessary information about the error
happened in the program. The exception is usually constructed and thrown implicitly, via CV_Error
and CV_Error_ macros, see error.
fastMalloc¶
void* fastMalloc(size_t size)¶
The function allocates buffer of the specified size and returns it. When the buffer size is 16
bytes or more, the returned buffer is aligned on 16 bytes.
fastFree¶
void fastFree(void* ptr)¶
The function deallocates the buffer, allocated with fastMalloc. If NULL pointer is passed,
the function does nothing.
format¶
string format(const char* fmt, ...)
The function acts like sprintf, but forms and returns STL string. It can be used for form
the error message in Exception constructor.
getNumThreads¶
int getNumThreads()¶
getThreadNum¶
int getThreadNum()¶
The function returns 0-based index of the currently executed thread. The function is only
valid inside a parallel OpenMP region. When OpenCV is built without OpenMP support, the
function always returns 0.
getTickCount¶
int64 getTickCount()¶
The function returns the number of ticks since the certain event (e.g. when the machine was
turned on). It can be used to initialize 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¶
double getTickFrequency()¶
The function returns the number of ticks per second. That is, the following code computes
the executing time in seconds.
double t = (double)getTickCount();
// do something ...
t = ((double)getTickCount() - t)/getTickFrequency();
setNumThreads¶
void setNumThreads(int nthreads)¶
Sets the number of threads used by OpenCV
The function sets the number of threads used by OpenCV in parallel OpenMP regions. If
nthreads=0, the function will use the default number of threads, which is usually equal to
the number of the processing cores.
Image Filtering¶
Functions and classes described in this section are used to perform various linear or non-linear
filtering operations on 2D images (represented as Mat‘s), that is, for each pixel location in the
source image some its (normally rectangular) neighborhood is considered and used to compute the
response. In case of a linear filter it is a weighted sum of pixel values, in case of morphological
operations it is the minimum or maximum etc. The computed response is stored to the destination
image at the same location . It means, that the output image will be of the same size as the
input image. Normally, the functions supports multi-channel arrays, in which case every channel is
processed independently, therefore the output image will also have the same number of channels as
the input one.
Another common feature of the functions and classes described in this section is that, unlike simple
arithmetic functions, they need to extrapolate values of some non-existing pixels. For example, if
we want to smooth an image using a Gaussian filter, then during the processing of the left-
most pixels in each row we need pixels to the left of them, i.e. outside of the image. We can let
those pixels be the same as the left-most image pixels (i.e. use “replicated border” extrapolation
method), or assume that all the non-existing pixels are zeros (“contant border” extrapolation
method) etc. OpenCV let the user to specify the extrapolation method; see the function
borderInterpolate and discussion of borderType parameter in various functions below.
BaseColumnFilter¶
Base class for filters with single-column kernels
class BaseColumnFilter
{
public:
virtual ~BaseColumnFilter();
The class BaseColumnFilter is the base class for filtering data using single-column kernels. The
filtering does not have to be a linear operation. In general, it could be written as following:
where is the filtering function, but, as it is represented as a class, it can produce any side effects,
memorize previously processed data etc. The class only defines the interface and is not used
directly. Instead, there are several functions in OpenCV (and you can add more) that return pointers
to the derived classes that implement specific filtering operations. Those pointers are then passed to
FilterEngine constructor. While the filtering operation interface uses uchar type, a particular
implementation is not limited to 8-bit data.
BaseFilter¶
Base class for 2D image filters
class BaseFilter
{
public:
virtual ~BaseFilter();
The class BaseFilter is the base class for filtering data using 2D kernels. The filtering does not have
to be a linear operation. In general, it could be written as following:
where is the filtering function. The class only defines the interface and is not used directly.
Instead, there are several functions in OpenCV (and you can add more) that return pointers to the
derived classes that implement specific filtering operations. Those pointers are then passed to
FilterEngine constructor. While the filtering operation interface uses uchar type, a particular
implementation is not limited to 8-bit data.
BaseRowFilter¶
Base class for filters with single-row kernels
class BaseRowFilter
{
public:
virtual ~BaseRowFilter();
The class BaseRowFilter is the base class for filtering data using single-row kernels. The filtering
does not have to be a linear operation. In general, it could be written as following:
where is the filtering function. The class only defines the interface and is not used directly.
Instead, there are several functions in OpenCV (and you can add more) that return pointers to the
derived classes that implement specific filtering operations. Those pointers are then passed to
FilterEngine constructor. While the filtering operation interface uses uchar type, a particular
implementation is not limited to 8-bit data.
FilterEngine¶
Generic image filtering class
class FilterEngine
{
public:
// empty constructor
FilterEngine();
// builds a 2D non-separable filter (!_filter2D.empty()) or
// a separable filter (!_rowFilter.empty() && !_columnFilter.empty())
// the input data type will be "srcType", the output data type will be
"dstType",
// the intermediate data type is "bufType".
// _rowBorderType and _columnBorderType determine how the image
// will be extrapolated beyond the image boundaries.
// _borderValue is only used when _rowBorderType and/or _columnBorderType
// == cv::BORDER_CONSTANT
FilterEngine(const Ptr<BaseFilter>& _filter2D,
const Ptr<BaseRowFilter>& _rowFilter,
const Ptr<BaseColumnFilter>& _columnFilter,
int srcType, int dstType, int bufType,
int _rowBorderType=BORDER_REPLICATE,
int _columnBorderType=-1, // use _rowBorderType by default
const Scalar& _borderValue=Scalar());
virtual ~FilterEngine();
// separate function for the engine initialization
void init(const Ptr<BaseFilter>& _filter2D,
const Ptr<BaseRowFilter>& _rowFilter,
const Ptr<BaseColumnFilter>& _columnFilter,
int srcType, int dstType, int bufType,
int _rowBorderType=BORDER_REPLICATE, int _columnBorderType=-1,
const Scalar& _borderValue=Scalar());
// starts filtering of the ROI in an image of size "wholeSize".
// returns the starting y-position in the source image.
virtual int start(Size wholeSize, Rect roi, int maxBufRows=-1);
// alternative form of start that takes the image
// itself instead of "wholeSize". Set isolated to true to pretend that
// there are no real pixels outside of the ROI
// (so that the pixels will be extrapolated using the specified border
modes)
virtual int start(const Mat& src, const Rect& srcRoi=Rect(0,0,-1,-1),
bool isolated=false, int maxBufRows=-1);
// processes the next portion of the source image,
// "srcCount" rows starting from "src" and
// stores the results to "dst".
// returns the number of produced rows
virtual int proceed(const uchar* src, int srcStep, int srcCount,
uchar* dst, int dstStep);
// higher-level function that processes the whole
// ROI or the whole image with a single call
virtual void apply( const Mat& src, Mat& dst,
const Rect& srcRoi=Rect(0,0,-1,-1),
Point dstOfs=Point(0,0),
bool isolated=false);
bool isSeparable() const { return filter2D.empty(); }
// how many rows from the input image are not yet processed
int remainingInputRows() const;
// how many output rows are not yet produced
int remainingOutputRows() const;
...
// the starting and the ending rows in the source image
int startY, endY;
The class FilterEngine can be used to apply an arbitrary filtering operation to an image. It contains
all the necessary intermediate buffers, it computes extrapolated values of the “virtual” pixels outside
of the image etc. Pointers to the initialized FilterEngine instances are returned by various
create*Filter functions, see below, and they are used inside high-level functions such as filter2D,
erode, dilate etc, that is, the class is the workhorse in many of OpenCV filtering functions.
This class makes it easier (though, maybe not very easy yet) to combine filtering operations with
other operations, such as color space conversions, thresholding, arithmetic operations, etc. By
combining several operations together you can get much better performance because your data will
stay in cache. For example, below is the implementation of Laplace operator for a floating-point
images, which is a simplified implementation of Laplacian:
// start filtering
int y = start(src, _srcRoi, isolated);
// process the whole ROI. Note that "endY - startY" is the total number
// of the source rows to process
// (including the possible rows outside of srcRoi but inside the source
image)
proceed( src.data + y*src.step,
(int)src.step, endY - startY,
dst.data + dstOfs.y*dst.step +
dstOfs.x*dst.elemSize(), (int)dst.step );
}
Unlike the earlier versions of OpenCV, now the filtering operations fully support the notion of
image ROI, that is, pixels outside of the ROI but inside the image can be used in the filtering
operations. For example, you can take a ROI of a single pixel and filter it - that will be a filter
response at that particular pixel (however, it’s possible to emulate the old behavior by passing
isolated=false to FilterEngine::start or FilterEngine::apply). You can pass the ROI explicitly to
FilterEngine::apply, or construct a new matrix headers:
// method 1:
// form a matrix header for a single value
float val1 = 0;
Mat dst1(1,1,CV_32F,&val1);
// method 2:
// form a matrix header for a single value
float val2 = 0;
Mat dst2(1,1,CV_32F,&val2);
bilateralFilter¶
void bilateralFilter(const Mat& src, Mat& dst, int d, double sigmaColor, double sigmaSpace,
int borderType=BORDER_DEFAULT)¶
blur¶
void blur(const Mat& src, Mat& dst, Size ksize, Point anchor=Point(-1, -1), int
borderType=BORDER_DEFAULT)
Smoothes image using normalized box filter
The call blur(src, dst, ksize, anchor, borderType) is equivalent to boxFilter(src, dst,
src.type(), anchor, true, borderType).
borderInterpolate¶
int borderInterpolate(int p, int len, int borderType)¶
The function computes and returns the coordinate of the donor pixel, corresponding to the
specified extrapolated pixel when using the specified extrapolation border mode. For
example, if we use BORDER_WRAP mode in the horizontal direction,
BORDER_REFLECT_101 in the vertical direction and want to compute value of the
“virtual” pixel Point(-5, 100) in a floating-point image img, it will be
boxFilter¶
void boxFilter(const Mat& src, Mat& dst, int ddepth, Size ksize, Point anchor=Point(-1, -1), bool
normalize=true, int borderType=BORDER_DEFAULT)¶
where
Unnormalized box filter is useful for computing various integral characteristics over each
pixel neighborhood, such as covariation matrices of image derivatives (used in dense optical
flow algorithms, [conerHarris]bgroup({Harris corner detector}) etc.). If you need to
compute pixel sums over variable-size windows, use integral.
buildPyramid¶
void buildPyramid(const Mat& src, vector<Mat>& dst, int maxlevel)¶
The function constructs a vector of images and builds the gaussian pyramid by recursively
applying pyrDown to the previously built pyramid layers, starting from dst[0]==src.
copyMakeBorder¶
void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right, int
borderType, const Scalar& value=Scalar())¶
The function copies the source image into the middle of the destination image. The areas to
the left, to the right, above and below the copied source image will be filled with
extrapolated pixels. This is not what FilterEngine or based on it filtering functions do (they
extrapolate pixels on-fly), but what other more complex functions, including your own, may
do to simplify image boundary handling.
The function supports the mode when src is already in the middle of dst. In this case the
function does not copy src itself, but simply constructs the border, e.g.:
createBoxFilter¶
Ptr<FilterEngine> createBoxFilter(int srcType, int dstType, Size ksize, Point anchor=Point(-1, -
1), bool normalize=true, int borderType=BORDER_DEFAULT)¶
Ptr<BaseRowFilter> getRowSumFilter(int srcType, int sumType, int ksize, int anchor=-1)¶
Ptr<BaseColumnFilter> getColumnSumFilter(int sumType, int dstType, int ksize, int anchor=-1,
double scale=1)¶
The function is a convenience function that retrieves horizontal sum primitive filter with
getRowSumFilter, vertical sum filter with getColumnSumFilter, constructs new FilterEngine
and passes both of the primitive filters there. The constructed filter engine can be used for
image filtering with normalized or unnormalized box filter.
createDerivFilter¶
Ptr<FilterEngine> createDerivFilter(int srcType, int dstType, int dx, int dy, int ksize, int
borderType=BORDER_DEFAULT)¶
The function createDerivFilter is a small convenience function that retrieves linear filter
coefficients for computing image derivatives using getDerivKernels and then creates a
separable linear filter with createSeparableLinearFilter. The function is used by Sobel and
Scharr.
createGaussianFilter¶
Ptr<FilterEngine> createGaussianFilter(int type, Size ksize, double sigmaX, double sigmaY=0,
int borderType=BORDER_DEFAULT)¶
The function createGaussianFilter computes Gaussian kernel coefficients and then returns
separable linear filter for that kernel. The function is used by GaussianBlur. Note that while
the function takes just one data type, both for input and output, you can pass by this
limitation by calling getGaussianKernel and then createSeparableFilter directly.
createLinearFilter¶
Ptr<FilterEngine> createLinearFilter(int srcType, int dstType, const Mat& kernel, Point
_anchor=Point(-1, -1), double delta=0, int rowBorderType=BORDER_DEFAULT, int
columnBorderType=-1, const Scalar& borderValue=Scalar())¶
Ptr<BaseFilter> getLinearFilter(int srcType, int dstType, const Mat& kernel, Point
anchor=Point(-1, -1), double delta=0, int bits=0)¶
The function returns pointer to 2D linear filter for the specified kernel, the source array type
and the destination array type. The function is a higher-level function that calls
getLinearFilter and passes the retrieved 2D filter to FilterEngine constructor.
createMorphologyFilter¶
Ptr<FilterEngine> createMorphologyFilter(int op, int type, const Mat& element, Point
anchor=Point(-1, -1), int rowBorderType=BORDER_CONSTANT, int columnBorderType=-1,
const Scalar& borderValue=morphologyDefaultBorderValue())¶
Ptr<BaseFilter> getMorphologyFilter(int op, int type, const Mat& element, Point anchor=Point(-
1, -1))¶
Ptr<BaseRowFilter> getMorphologyRowFilter(int op, int type, int esize, int anchor=-1)¶
Ptr<BaseColumnFilter> getMorphologyColumnFilter(int op, int type, int esize, int anchor=-1)¶
static inline Scalar morphologyDefaultBorderValue(){ return Scalar::all(DBL_MAX)¶
createSeparableLinearFilter¶
Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstType, const Mat&
rowKernel, const Mat& columnKernel, Point anchor=Point(-1, -1), double delta=0, int
rowBorderType=BORDER_DEFAULT, int columnBorderType=-1, const Scalar&
borderValue=Scalar())¶
Ptr<BaseColumnFilter> getLinearColumnFilter(int bufType, int dstType, const Mat&
columnKernel, int anchor, int symmetryType, double delta=0, int bits=0)¶
Ptr<BaseRowFilter> getLinearRowFilter(int srcType, int bufType, const Mat& rowKernel, int
anchor, int symmetryType)¶
The functions construct primitive separable linear filtering operations or a filter engine
based on them. Normally it’s enough to use createSeparableLinearFilter or even higher-
level sepFilter2D. The function createMorphologyFilter is smart enough to figure out the
symmetryType for each of the two kernels, the intermediate bufType, and, if the filtering
can be done in integer arithmetics, the number of bits to encode the filter coefficients. If it
does not work for you, it’s possible to call getLinearColumnFilter, getLinearRowFilter
directly and then pass them to FilterEngine constructor.
The function dilates the source image using the specified structuring element that determines
the shape of a pixel neighborhood over which the maximum is taken:
The function supports the in-place mode. Dilation can be applied several (iterations) times.
In the case of multi-channel images each channel is processed independently.
erode¶
void erode(const Mat& src, Mat& dst, const Mat& element, Point anchor=Point(-1, -1), int
iterations=1, int borderType=BORDER_CONSTANT, const Scalar&
borderValue=morphologyDefaultBorderValue())
The function erodes the source image using the specified structuring element that determines
the shape of a pixel neighborhood over which the minimum is taken:
The function supports the in-place mode. Erosion can be applied several (iterations) times.
In the case of multi-channel images each channel is processed independently.
filter2D¶
void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1, -
1), double delta=0, int borderType=BORDER_DEFAULT)¶
The function applies an arbitrary linear filter to the image. In-place operation is supported.
When the aperture is partially outside the image, the function interpolates outlier pixel
values according to the specified border mode.
GaussianBlur¶
void GaussianBlur(const Mat& src, Mat& dst, Size ksize, double sigmaX, double sigmaY=0, int
borderType=BORDER_DEFAULT)¶
The function convolves the source image with the specified Gaussian kernel. In-place
filtering is supported.
getDerivKernels¶
void getDerivKernels(Mat& kx, Mat& ky, int dx, int dy, int ksize, bool normalize=false, int
ktype=CV_32F)¶
• kx – The output matrix of row filter coefficients; will have type ktype
• ky – The output matrix of column filter coefficients; will have type
Parameters: ktype
• dx – The derivative order in respect with x
• dy – The derivative order in respect with y
• ksize – The aperture size. It can be CV_SCHARR, 1, 3, 5 or 7
• normalize – Indicates, whether to normalize (scale down) the filter
coefficients or not. In theory the coefficients should have the
denominator . If you are going to filter floating-
point images, you will likely want to use the normalized kernels. But if
you compute derivatives of a 8-bit image, store the results in 16-bit
image and wish to preserve all the fractional bits, you may want to set
normalize=false.
• ktype – The type of filter coefficients. It can be CV_32f or CV_64F
The function computes and returns the filter coefficients for spatial image derivatives. When
ksize=CV_SCHARR, the Scharr kernels are generated, see Scharr. Otherwise, Sobel
kernels are generated, see Sobel. The filters are normally passed to sepFilter2D or to
createSeparableLinearFilter.
getGaussianKernel¶
Mat getGaussianKernel(int ksize, double sigma, int ktype=CV_64F)¶
The function computes and returns the matrix of Gaussian filter coefficients:
getKernelType¶
int getKernelType(const Mat& kernel, Point anchor)¶
The function analyzes the kernel coefficients and returns the corresponding kernel type:
getStructuringElement¶
Mat getStructuringElement(int shape, Size esize, Point anchor=Point(-1, -1))¶
Returns the structuring element of the specified size and shape for morphological operations
• shape –
medianBlur¶
void medianBlur(const Mat& src, Mat& dst, int ksize)¶
The function smoothes image using the median filter with aperture. Each
channel of a multi-channel image is processed independently. In-place operation is
supported.
morphologyEx¶
void morphologyEx(const Mat& src, Mat& dst, int op, const Mat& element, Point anchor=Point(-
1, -1), int iterations=1, int borderType=BORDER_CONSTANT, const Scalar&
borderValue=morphologyDefaultBorderValue())¶
The function can perform advanced morphological transformations using erosion and
dilation as basic operations.
Opening:
Closing:
Morphological gradient:
“Top hat”:
“Black hat”:
Laplacian¶
void Laplacian(const Mat& src, Mat& dst, int ddepth, int ksize=1, double scale=1, double
delta=0, int borderType=BORDER_DEFAULT)¶
This is done when ksize > 1. When ksize == 1, the Laplacian is computed by filtering the
image with the following aperture:
pyrDown¶
void pyrDown(const Mat& src, Mat& dst, const Size& dstsize=Size())¶
The function performs the downsampling step of the Gaussian pyramid construction. First it
convolves the source image with the kernel:
and then downsamples the image by rejecting even rows and columns.
pyrUp¶
void pyrUp(const Mat& src, Mat& dst, const Size& dstsize=Size())¶
Upsamples an image and then smoothes it
The function performs the upsampling step of the Gaussian pyramid construction (it can
actually be used to construct the Laplacian pyramid). First it upsamples the source image by
injecting even zero rows and columns and then convolves the result with the same kernel as
in pyrDown, multiplied by 4.
sepFilter2D¶
void sepFilter2D(const Mat& src, Mat& dst, int ddepth, const Mat& rowKernel, const Mat&
columnKernel, Point anchor=Point(-1, -1), double delta=0, int
borderType=BORDER_DEFAULT)¶
The function applies a separable linear filter to the image. That is, first, every row of src is
filtered with 1D kernel rowKernel. Then, every column of the result is filtered with 1D
kernel columnKernel and the final result shifted by delta is stored in dst.
Sobel¶
void Sobel(const Mat& src, Mat& dst, int ddepth, int xorder, int yorder, int ksize=3, double
scale=1, double delta=0, int borderType=BORDER_DEFAULT)¶
Calculates the first, second, third or mixed image derivatives using an extended Sobel
operator
There is also the special value ksize = CV_SCHARR (-1) that corresponds to a
Scharr filter that may give more accurate results than a Sobel. The Scharr aperture is
The function calculates the image derivative by convolving the image with the appropriate
kernel:
The Sobel operators combine Gaussian smoothing and differentiation, so the result is more
or less resistant to the noise. Most often, the function is called with (xorder = 1, yorder = 0,
ksize = 3) or (xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image
derivative. The first case corresponds to a kernel of:
Scharr¶
void Scharr(const Mat& src, Mat& dst, int ddepth, int xorder, int yorder, double scale=1, double
delta=0, int borderType=BORDER_DEFAULT)¶
The function computes the first x- or y- spatial image derivative using Scharr operator. The
call
is equivalent to
The actual implementations of the geometrical transformations, from the most generic remap and to
the simplest and the fastest resize, need to solve the 2 main problems with the above formula:
convertMaps¶
void convertMaps(const Mat& map1, const Mat& map2, Mat& dstmap1, Mat& dstmap2, int
dstmap1type, bool nninterpolation=false)¶
getAffineTransform¶
Mat getAffineTransform(const Point2f src[], const Point2f dst[] )¶
where
getPerspectiveTransform¶
Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[] )¶
where
getRectSubPix¶
void getRectSubPix(const Mat& image, Size patchSize, Point2f center, Mat& dst, int patchType=-
1) ¶
where the values of the pixels at non-integer coordinates are retrieved using bilinear
interpolation. Every channel of multiple-channel images is processed independently. While
the rectangle center must be inside the image, parts of the rectangle may be outside. In this
case, the replication border mode (see borderInterpolate) is used to extrapolate the pixel
values outside of the image.
getRotationMatrix2D¶
Mat getRotationMatrix2D(Point2f center, double angle, double scale)¶
Calculates the affine matrix of 2d rotation.
where
The transformation maps the rotation center to itself. If this is not the purpose, the shift
should be adjusted.
invertAffineTransform¶
void invertAffineTransform(const Mat& M, Mat& iM)¶
remap¶
void remap(const Mat& src, Mat& dst, const Mat& map1, const Mat& map2, int interpolation, int
borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
The function remap transforms the source image using the specified map:
Where values of pixels with non-integer coordinates are computed using one of the available
interpolation methods. and can be encoded as separate floating-point maps,
interleaved floating-point maps or fixed-point maps. The function can not operate in-place.
resize¶
void resize(const Mat& src, Mat& dst, Size dsize, double fx=0, double fy=0, int
interpolation=INTER_LINEAR)
Resizes an image
The function resize resizes an image src down to or up to the specified size. Note that the
initial dst type or size are not taken into account. Instead the size and type are derived from
the src, dsize, fx and fy. If you want to resize src so that it fits the pre-created dst, you
may call the function as:
If you want to decimate the image by factor of 2 in each direction, you can call the function
this way:
warpAffine¶
void warpAffine(const Mat& src, Mat& dst, const Mat& M, Size dsize, int flags=INTER_LINEAR,
int borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())¶
when the flag WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with
invertAffineTransform and then put in the formula above instead of M. The function can not
operate in-place.
warpPerspective¶
void warpPerspective(const Mat& src, Mat& dst, const Mat& M, Size dsize, int
flags=INTER_LINEAR, int borderMode=BORDER_CONSTANT, const Scalar&
borderValue=Scalar())¶
The function warpPerspective transforms the source image using the specified matrix:
when the flag WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with
invert and then put in the formula above instead of M. The function can not operate in-place.
• ADAPTIVE_THRESH_GAUSSIAN_C - (
• THRESH_BINARY_INV - None
param blockSize:
The size of a pixel neighborhood that is used to calculate a threshold value for the
pixel: 3, 5, 7, and so on
param The constant subtracted from the mean or weighted mean (see the discussion);
C: normally, it’s positive, but may be zero or negative as well
The function transforms a grayscale image to a binary image according to the formulas:
• THRESH_BINARY -
• THRESH_BINARY_INV -
cvtColor¶
void cvtColor(const Mat& src, Mat& dst, int code, int dstCn=0)¶
The function converts the input image from one color space to another. In the case of
transformation to-from RGB color space the ordering of the channels should be specified
explicitly (RGB or BGR).
Of course, in the case of linear transformations the range does not matter, but in the non-
linear cases the input RGB image should be normalized to the proper value range in order to
get the correct results, e.g. for RGB:math:$rightarrow $`L*u*v* transformation. For
example, if you have a 32-bit floating-point image directly converted from 8-bit image
without any scaling, then it will have 0..255 value range, instead of the assumed by the
function 0..1. So, before calling :cfunc:`cvtColor(), you need first to scale the image down:
img *= 1./255;
cvtColor(img, img, CV_BGR2Luv);
Some more advanced channel reordering can also be done with mixChannels.
• RGB CIE XYZ.Rec 709 with D65 white point (CV_BGR2XYZ, CV_RGB2XYZ,
CV_XYZ2BGR, CV_XYZ2RGB):
, and cover the whole value range (in the case of floating-point images may exceed
1).
where
if then
On output , , .
• 8-bit images *
• 32-bit images *
H, S, V are left as is
• 8-bit images *
• 32-bit images *
H, S, V are left as is
where
and
On output , ,
• 16-bit images *
• 32-bit images *
L, a, b are left as is
On output , , .
• 8-bit images *
• 16-bit images *
• 32-bit images *
L, u, v are left as is
The above formulas for converting RGB to/from various color spaces have been taken from
multiple sources on Web, primarily from the Charles Poynton site
http://www.poynton.com/ColorFAQ.html
The output RGB components of a pixel are interpolated from 1, 2 or 4 neighbors of the pixel
having the same color. There are several modifications of the above pattern that can be
achieved by shifting the pattern one pixel left and/or one pixel up. The two letters and
in the conversion constants CV_Bayer 2BGR and CV_Bayer 2RGB indicate the
particular pattern type - these are components from the second row, second and third
columns, respectively. For example, the above pattern has very popular “BG” type.
distanceTransform¶
void distanceTransform(const Mat& src, Mat& dst, int distanceType, int maskSize)¶
void distanceTransform(const Mat& src, Mat& dst, Mat& labels, int distanceType, int maskSize)
Calculates the distance to the closest zero pixel for each pixel of the source image.
The functions distanceTransform calculate the approximate or precise distance from every
binary image pixel to the nearest zero pixel. (for zero image pixels the distance will
obviously be zero).
When maskSize == CV_DIST_MASK_PRECISE and distanceType == CV_DIST_L2, the
function runs the algorithm described in .
In other cases the algorithm is used, that is, for pixel the function finds the shortest path to
the nearest zero pixel consisting of basic shifts: horizontal, vertical, diagonal or knight’s
move (the latest is available for a mask). The overall distance is calculated as a sum
of these basic distances. Because the distance function should be symmetric, all of the
horizontal and vertical shifts must have the same cost (that is denoted as a), all the diagonal
shifts must have the same cost (denoted b), and all knight’s moves must have the same cost
(denoted c). For CV_DIST_C and CV_DIST_L1 types the distance is calculated precisely,
whereas for CV_DIST_L2 (Euclidian distance) the distance can be calculated only with some
relative error (a mask gives more accurate results). For a, b and c OpenCV uses the
values suggested in the original paper:
CV_DIST_C a = 1, b = 1
CV_DIST_L1 a = 1, b = 2
CV_DIST_L2 a=0.955, b=1.3693
CV_DIST_L2 a=1, b=1.4, c=2.1969
Typically, for a fast, coarse distance estimation CV_DIST_L2, a mask is used, and for a
more accurate distance estimation CV_DIST_L2, a mask or the precise algorithm is
used. Note that both the precise and the approximate algorithms are linear on the number of
pixels.
The second variant of the function does not only compute the minimum distance for each
pixel , but it also identifies the nearest the nearest connected component consisting of
zero pixels. Index of the component is stored in . The connected components
of zero pixels are also found and marked by the function.
In this mode the complexity is still linear. That is, the function provides a very fast way to
compute Voronoi diagram for the binary image. Currently, this second variant can only use
the approximate distance transform algorithm.
floodFill¶
int floodFill(Mat& image, Point seed, Scalar newVal, Rect* rect=0, Scalar loDiff=Scalar(),
Scalar upDiff=Scalar(), int flags=4)¶
int floodFill(Mat& image, Mat& mask, Point seed, Scalar newVal, Rect* rect=0, Scalar
loDiff=Scalar(), Scalar upDiff=Scalar(), int flags=4)
The functions floodFill fill a connected component starting from the seed point with the
specified color. The connectivity is determined by the color/brightness closeness of the
neighbor pixels. The pixel at is considered to belong to the repainted domain if:
where is the value of one of pixel neighbors that is already known to belong to
the component. That is, to be added to the connected component, a pixel’s color/brightness
should be close enough to the:
• color/brightness of one of its neighbors that are already referred to the connected
component in the case of floating range
• color/brightness of the seed point in the case of fixed range.
By using these functions you can either mark a connected component with the specified
color in-place, or build a mask and then extract the contour or copy the region to another
image etc. Various modes of the function are demonstrated in floodfill.c sample.
inpaint¶
void inpaint(const Mat& src, const Mat& inpaintMask, Mat& dst, double inpaintRadius, int flags)
The function reconstructs the selected image area from the pixel near the area boundary. The
function may be used to remove dust and scratches from a scanned photo, or to remove
undesirable objects from still images or video. See http://en.wikipedia.org/wiki/Inpainting
for more details.
integral¶
void integral(const Mat& image, Mat& sum, int sdepth=-1)
void integral(const Mat& image, Mat& sum, Mat& sqsum, int sdepth=-1)
void integral(const Mat& image, Mat& sum, Mat& sqsum, Mat& tilted, int sdepth=-1)
The functions integral calculate one or more integral images for the source image as
following:
Using these integral images, one may calculate sum, mean and standard deviation over a
specific up-right or rotated rectangular region of the image in a constant time, for example:
It makes possible to do a fast blurring or fast block correlation with variable window size,
for example. In the case of multi-channel images, sums for each channel are accumulated
independently.
threshold¶
double threshold(const Mat& src, Mat& dst, double thresh, double maxVal, int thresholdType)
• THRESH_BINARY -
• THRESH_BINARY_INV -
• THRESH_TRUNC -
• THRESH_TOZERO -
• THRESH_TOZERO_INV -
Also, the special value THRESH_OTSU may be combined with one of the above values. In this
case the function determines the optimal threshold value using Otsu’s algorithm and uses it
instead of the specified thresh. The function returns the computed threshold value.
Currently, Otsu’s method is implemented only for 8-bit images.
See also: adaptiveThreshold, findContours, compare, min, max
watershed¶
void watershed(const Mat& image, Mat& markers)
Note, that it is not necessary that every two neighbor connected components are separated
by a watershed boundary (-1’s pixels), for example, in case when such tangent components
exist in the initial marker image. Visual demonstration and usage example of the function
can be found in OpenCV samples directory; see watershed.cpp demo.
Histograms¶
calcHist¶
void calcHist(const Mat* arrays, int narrays, const int* channels, const Mat& mask, MatND&
hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false)¶
void calcHist(const Mat* arrays, int narrays, const int* channels, const Mat& mask, SparseMat&
hist, int dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false)
• arrays – Source arrays. They all should have the same depth, CV_8U or
CV_32F, and the same size. Each of them can have an arbitrary number
of channels
• narrays – The number of source arrays
• channels – The list of dims channels that are used to compute the
histogram. The first array channels are numerated from 0 to
arrays[0].channels()-1, the second array channels are counted from
arrays[0].channels() to arrays[0].channels() +
arrays[1].channels()-1 etc.
Parameter
• mask – The optional mask. If the matrix is not empty, it must be 8-bit
s:
array of the same size as arrays[i]. The non-zero mask elements mark
the array elements that are counted in the histogram
• hist – The output histogram, a dense or sparse dims-dimensional array
• dims – The histogram dimensionality; must be positive and not greater
than :cmacro:`CV_MAX_DIMS`(=32 in the current OpenCV version)
• histSize – The array of histogram sizes in each dimension
• ranges – The array of dims arrays of the histogram bin boundaries in
each dimension. When the histogram is uniform (uniform``=true),
then for each dimension ``i it’s enough to specify the lower
(inclusive) boundary of the 0-th histogram bin and the upper
(exclusive) boundary for the last histogram bin
histSize[i]-1. That is, in the case of uniform histogram each of
ranges[i] is an array of 2 elements. When the histogram is not
uniform (uniform=false), then each of ranges[i] contains
histSize[i]+1 elements:
The functions calcHist calculate the histogram of one or more arrays. The elements of a
tuple that is used to increment a histogram bin are taken at the same location from the
corresponding input arrays. The sample below shows how to compute 2D Hue-Saturation
histogram for a color imag
#include <cv.h>
#include <highgui.h>
Mat hsv;
cvtColor(src, hsv, CV_BGR2HSV);
namedWindow( "Source", 1 );
imshow( "Source", src );
waitKey();
}
calcBackProject¶
void calcBackProject(const Mat* arrays, int narrays, const int* channels, const MatND& hist,
Mat& backProject, const float** ranges, double scale=1, bool uniform=true)¶
void calcBackProject(const Mat* arrays, int narrays, const int* channels, const SparseMat&
hist, Mat& backProject, const float** ranges, double scale=1, bool uniform=true)
• arrays – Source arrays. They all should have the same depth, CV_8U or
CV_32F, and the same size. Each of them can have an arbitrary number
of channels
• narrays – The number of source arrays
• channels – The list of channels that are used to compute the back
projection. The number of channels must match the histogram
dimensionality. The first array channels are numerated from 0 to
arrays[0].channels()-1, the second array channels are counted
from arrays[0].channels() to arrays[0].channels() +
Parameters:
arrays[1].channels()-1 etc.
• hist – The input histogram, a dense or sparse
• backProject – Destination back projection aray; will be a single-
channel array of the same size and the same depth as arrays[0]
• ranges – The array of arrays of the histogram bin boundaries in each
dimension. See calcHist
• scale – The optional scale factor for the output back projection
• uniform – Indicates whether the histogram is uniform or not, see above
The functions calcBackProject calculate the back project of the histogram. That is,
similarly to calcHist, at each location (x, y) the function collects the values from the
selected channels in the input images and finds the corresponding histogram bin. But instead
of incrementing it, the function reads the bin value, scales it by scale and stores in
backProject(x,y). In terms of statistics, the function computes probability of each
element value in respect with the empirical probability distribution represented by the
histogram. Here is how, for example, you can find and track a bright-colored object in a
scene:
• Before the tracking, show the object to the camera such that covers almost the whole
frame. Calculate a hue histogram. The histogram will likely have a strong
maximums, corresponding to the dominant colors in the object.
• During the tracking, calculate back projection of a hue plane of each input video
frame using that pre-computed histogram. Threshold the back projection to suppress
weak colors. It may also have sense to suppress pixels with non sufficient color
saturation and too dark or too bright pixels.
• Find connected components in the resulting picture and choose, for example, the
largest component.
compareHist¶
double compareHist(const MatND& H1, const MatND& H2, int method)¶
double compareHist(const SparseMat& H1, const SparseMat& H2, int method)
The functions compareHist compare two dense or two sparse histograms using the
specified method:
• Correlation (method=CV_COMP_CORREL) *
where
and is the total number of histogram bins.
• Chi-Square (method=CV_COMP_CHISQR) *
• Intersection (method=CV_COMP_INTERSECT) *
While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be
suitable for high-dimensional sparse histograms, where, because of aliasing and sampling
problems the coordinates of non-zero histogram bins can slightly shift. To compare such
histograms or more general sparse configurations of weighted points, consider using the
calcEMD function.
equalizeHist¶
void equalizeHist(const Mat& src, Mat& dst)¶
The function equalizes the histogram of the input image using the following algorithm:
The algorithm normalizes the brightness and increases the contrast of the image.
Feature Detection¶
Canny¶
void Canny(const Mat& image, Mat& edges, double threshold1, double threshold2, int
apertureSize=3, bool L2gradient=false)¶
The function finds edges in the input image image and marks them in the output map edges
using the Canny algorithm. The smallest value between threshold1 and threshold2 is
used for edge linking, the largest value is used to find the initial segments of strong edges,
see http://en.wikipedia.org/wiki/Canny_edge_detector
cornerEigenValsAndVecs¶
void cornerEigenValsAndVecs(const Mat& src, Mat& dst, int blockSize, int apertureSize, int
borderType=BORDER_DEFAULT)¶
After that it finds eigenvectors and eigenvalues of and stores them into destination image
in the form where
• *
• *
• *
The output of the function can be used for robust edge or corner detection.
cornerHarris¶
void cornerHarris(const Mat& src, Mat& dst, int blockSize, int apertureSize, double k, int
borderType=BORDER_DEFAULT)¶
The function runs the Harris edge detector on the image. Similarly to cornerMinEigenVal
and cornerEigenValsAndVecs, for each pixel it calculates a gradient
covariation matrix over a neighborhood. Then, it
computes the following characteristic:
Corners in the image can be found as the local maxima of this response map.
cornerMinEigenVal¶
void cornerMinEigenVal(const Mat& src, Mat& dst, int blockSize, int apertureSize=3, int
borderType=BORDER_DEFAULT)¶
The function is similar to cornerEigenValsAndVecs but it calculates and stores only the
minimal eigenvalue of the covariation matrix of derivatives, i.e. in terms of the
formulae in cornerEigenValsAndVecs description.
cornerSubPix¶
void cornerSubPix(const Mat& image, vector<Point2f>& corners, Size winSize, Size zeroZone,
TermCriteria criteria)¶
The function iterates to find the sub-pixel accurate location of corners, or radial saddle
points, as shown in on the picture below.
Sub-pixel accurate corner locator is based on the observation that every vector from the
center to a point located within a neighborhood of is orthogonal to the image gradient
at subject to image and measurement noise. Consider the expression:
where is the image gradient at the one of the points in a neighborhood of . The
value of is to be found such that is minimized. A system of equations may be set up with
set to zero:
where the gradients are summed within a neighborhood (“search window”) of . Calling the
first gradient term and the second gradient term gives:
The algorithm sets the center of the neighborhood window at this new center and then
iterates until the center keeps within a set threshold.
goodFeaturesToTrack¶
void goodFeaturesToTrack(const Mat& image, vector<Point2f>& corners, int maxCorners,
double qualityLevel, double minDistance, const Mat& mask=Mat(), int blockSize=3, bool
useHarrisDetector=false, double k=0.04)¶
The function finds the most prominent corners in the image or in the specified image region,
as described in :
• the function first calculates the corner quality measure at every source image pixel
using the cornerMinEigenVal or cornerHarris
• then it performs non-maxima suppression (the local maxima in neighborhood
are retained).
• the next step rejects the corners with the minimal eigenvalue less than
.
• the remaining corners are then sorted by the quality measure in the descending order.
• finally, the function throws away each corner if there is a stronger corner (
) such that the distance between them is less than minDistance
HoughCircles¶
void HoughCircles(Mat& image, vector<Vec3f>& circles, int method, double dp, double minDist,
double param1=100, double param2=100, int minRadius=0, int maxRadius=0)¶
Finds circles in a grayscale image using a Hough transform.
The function finds circles in a grayscale image using some modification of Hough
transform. Here is a short usage example:
#include <cv.h>
#include <highgui.h>
#include <math.h>
Note that usually the function detects the circles’ centers well, however it may fail to find
the correct radii. You can assist the function by specifying the radius range (minRadius and
maxRadius) if you know it, or you may ignore the returned radius, use only the center and
find the correct radius using some additional procedure.
HoughLines¶
void HoughLines(Mat& image, vector<Vec2f>& lines, double rho, double theta, int threshold,
double srn=0, double stn=0)¶
The function implements standard or standard multi-scale Hough transform algorithm for
line detection. See HoughLinesP for the code example.
HoughLinesP¶
void HoughLinesP(Mat& image, vector<Vec4i>& lines, double rho, double theta, int threshold,
double minLineLength=0, double maxLineGap=0)¶
The function implements probabilistic Hough transform algorithm for line detection,
described in . Below is line detection example:
#if 0
vector<Vec2f> lines;
HoughLines( dst, lines, 1, CV_PI/180, 100 );
waitKey(0);
return 0;
}
This is the sample picture the function parameters have been tuned for:
And this is the output of the above program in the case of probabilistic Hough transform
perCornerDetect¶
void preCornerDetect(const Mat& src, Mat& dst, int apertureSize, int
borderType=BORDER_DEFAULT)¶
The function calculates the complex spatial derivative-based function of the source image
where , are the first image derivatives, , are the second image derivatives
and is the mixed derivative.
The corners can be found as local maximums of the functions, as shown below:
KeyPoint¶
Data structure for salient point detectors
KeyPoint
{
public:
// default constructor
KeyPoint();
// two complete constructors
KeyPoint(Point2f _pt, float _size, float _angle=-1,
float _response=0, int _octave=0, int _class_id=-1);
KeyPoint(float x, float y, float _size, float _angle=-1,
float _response=0, int _octave=0, int _class_id=-1);
// coordinate of the point
Point2f pt;
// feature size
float size;
// feature orintation in degrees
// (has negative value if the orientation
// is not defined/not computed)
float angle;
// feature strength
// (can be used to select only
// the most prominent key points)
float response;
// scale-space octave in which the feature has been found;
// may correlate with the size
int octave;
// point (can be used by feature
// classifiers or object detectors)
int class_id;
};
MSER¶
Maximally-Stable Extremal Region Extractor
SURF¶
Class for extracting Speeded Up Robust Features from an image.
The class SURF implements Speeded Up Robust Features descriptor . There is fast multi-scale
Hessian keypoint detector that can be used to find the keypoints (which is the default option), but
the descriptors can be also computed for the user-specified keypoints. The function can be used for
object tracking and localization, image stitching etc. See the find_obj.cpp demo in OpenCV
samples directory.
StarDetector¶
Implements Star keypoint detector
The functions accumulate* can be used, for example, to collect statistic of background of a
scene, viewed by a still camera, for the further foreground-background segmentation.
accumulateSquare¶
void accumulateSquare(const Mat& src, Mat& dst, const Mat& mask=Mat())¶
Adds the square of the source image to the accumulator.
The function adds the input image src or its selected region, raised to power 2, to the
accumulator dst:
accumulateProduct¶
void accumulateProduct(const Mat& src1, const Mat& src2, Mat& dst, const Mat&
mask=Mat())¶
The function adds the product of 2 images or their selected regions to the accumulator dst:
accumulateWeighted¶
void accumulateWeighted(const Mat& src, Mat& dst, double alpha, const Mat& mask=Mat())¶
The function calculates the weighted sum of the input image src and the accumulator dst
so that dst becomes a running average of frame sequence:
that is, alpha regulates the update speed (how fast the accumulator “forgets” about earlier
images). The function supports multi-channel images; each channel is processed
independently.
calcOpticalFlowPyrLK¶
void calcOpticalFlowPyrLK(const Mat& prevImg, const Mat& nextImg, const vector<Point2f>&
prevPts, vector<Point2f>& nextPts, vector<uchar>& status, vector<float>& err, Size
winSize=Size(15, 15), int maxLevel=3, TermCriteria
criteria=TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), double
derivLambda=0.5, int flags=0)¶
Calculates the optical flow for a sparse feature set using the iterative Lucas-Kanade method
with pyramids
The function implements the sparse iterative version of the Lucas-Kanade optical flow in
pyramids, see .
calcOpticalFlowFarneback¶
void calcOpticalFlowFarneback(const Mat& prevImg, const Mat& nextImg, Mat& flow, double
pyrScale, int levels, int winsize, int iterations, int polyN, double polySigma, int flags)¶
The function finds optical flow for each prevImg pixel using the alorithm so that
updateMotionHistory¶
void updateMotionHistory(const Mat& silhouette, Mat& mhi, double timestamp, double
duration)¶
• silhouette – Silhouette mask that has non-zero pixels where the motion
occurs
• mhi – Motion history image, that is updated by the function (single-
Parameters: channel, 32-bit floating-point)
• timestamp – Current time in milliseconds or other units
• duration – Maximal duration of the motion track in the same units as
timestamp
That is, MHI pixels where motion occurs are set to the current timestamp, while the pixels
where motion happened last time a long time ago are cleared.
calcMotionGradient¶
void calcMotionGradient(const Mat& mhi, Mat& mask, Mat& orientation, double delta1, double
delta2, int apertureSize=3)¶
(in fact, fastArctan and phase are used, so that the computed angle is measured in degrees
and covers the full range 0..360). Also, the mask is filled to indicate pixels where the
computed angle is valid.
calcGlobalOrientation¶
double calcGlobalOrientation(const Mat& orientation, const Mat& mask, const Mat& mhi,
double timestamp, double duration)¶
The function calculates the average motion direction in the selected region and returns the
angle between 0 degrees and 360 degrees. The average direction is computed from the
weighted orientation histogram, where a recent motion has larger weight and the motion
occurred in the past has smaller weight, as recorded in mhi.
CamShift¶
RotatedRect CamShift(const Mat& probImage, Rect& window, TermCriteria criteria)¶
The function implements the CAMSHIFT object tracking algrorithm Bradski98. First, it
finds an object center using meanShift and then adjust the window size and finds the optimal
rotation. The function returns the rotated rectangle structure that includes the object position,
size and the orientation. The next position of the search window can be obtained with
RotatedRect::boundingRect().
meanShift¶
int meanShift(const Mat& probImage, Rect& window, TermCriteria criteria)¶
The function implements iterative object search algorithm. It takes the object back
projection on input and the initial position. The mass center in window of the back projection
image is computed and the search window center shifts to the mass center. The procedure is
repeated until the specified number of iterations criteria.maxCount is done or until the
window center shifts by less than criteria.epsilon. The algorithm is used inside
CamShift and, unlike CamShift, the search window size or orientation do not change during
the search. You can simply pass the output of calcBackProject to this function, but better
results can be obtained if you pre-filter the back projection and remove the noise (e.g. by
retrieving connected components with findContours, throwing away contours with small
area (contourArea) and rendering the remaining contours with drawContours)
KalmanFilter¶
Kalman filter class
class KalmanFilter
{
public:
KalmanFilter();newline
KalmanFilter(int dynamParams, int measureParams, int
controlParams=0);newline
void init(int dynamParams, int measureParams, int controlParams=0);newline
// predicts statePre from statePost
const Mat& predict(const Mat& control=Mat());newline
// corrects statePre based on the input measurement vector
// and stores the result to statePost.
const Mat& correct(const Mat& measurement);newline
The functions accumulate* can be used, for example, to collect statistic of background of a
scene, viewed by a still camera, for the further foreground-background segmentation.
accumulateSquare¶
void accumulateSquare(const Mat& src, Mat& dst, const Mat& mask=Mat())¶
The function adds the input image src or its selected region, raised to power 2, to the
accumulator dst:
accumulateProduct¶
void accumulateProduct(const Mat& src1, const Mat& src2, Mat& dst, const Mat&
mask=Mat())¶
The function adds the product of 2 images or their selected regions to the accumulator dst:
The function supports multi-channel images; each channel is processed independently.
accumulateWeighted¶
void accumulateWeighted(const Mat& src, Mat& dst, double alpha, const Mat& mask=Mat())¶
The function calculates the weighted sum of the input image src and the accumulator dst
so that dst becomes a running average of frame sequence:
that is, alpha regulates the update speed (how fast the accumulator “forgets” about earlier
images). The function supports multi-channel images; each channel is processed
independently.
calcOpticalFlowPyrLK¶
void calcOpticalFlowPyrLK(const Mat& prevImg, const Mat& nextImg, const vector<Point2f>&
prevPts, vector<Point2f>& nextPts, vector<uchar>& status, vector<float>& err, Size
winSize=Size(15, 15), int maxLevel=3, TermCriteria
criteria=TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), double
derivLambda=0.5, int flags=0)¶
Calculates the optical flow for a sparse feature set using the iterative Lucas-Kanade method
with pyramids
The function implements the sparse iterative version of the Lucas-Kanade optical flow in
pyramids, see .
calcOpticalFlowFarneback¶
void calcOpticalFlowFarneback(const Mat& prevImg, const Mat& nextImg, Mat& flow, double
pyrScale, int levels, int winsize, int iterations, int polyN, double polySigma, int flags)¶
The function finds optical flow for each prevImg pixel using the alorithm so that
updateMotionHistory¶
void updateMotionHistory(const Mat& silhouette, Mat& mhi, double timestamp, double
duration)¶
• silhouette – Silhouette mask that has non-zero pixels where the motion
occurs
• mhi – Motion history image, that is updated by the function (single-
channel, 32-bit floating-point)
Parameters:
• timestamp – Current time in milliseconds or other units
• duration – Maximal duration of the motion track in the same units as
timestamp
That is, MHI pixels where motion occurs are set to the current timestamp, while the pixels
where motion happened last time a long time ago are cleared.
The function, together with calcMotionGradient and calcGlobalOrientation, implements the
motion templates technique, described in and . See also the OpenCV sample motempl.c that
demonstrates the use of all the motion template functions.
calcMotionGradient¶
void calcMotionGradient(const Mat& mhi, Mat& mask, Mat& orientation, double delta1, double
delta2, int apertureSize=3)¶
(in fact, fastArctan and phase are used, so that the computed angle is measured in degrees
and covers the full range 0..360). Also, the mask is filled to indicate pixels where the
computed angle is valid.
calcGlobalOrientation¶
double calcGlobalOrientation(const Mat& orientation, const Mat& mask, const Mat& mhi,
double timestamp, double duration)¶
The function calculates the average motion direction in the selected region and returns the
angle between 0 degrees and 360 degrees. The average direction is computed from the
weighted orientation histogram, where a recent motion has larger weight and the motion
occurred in the past has smaller weight, as recorded in mhi.
CamShift¶
RotatedRect CamShift(const Mat& probImage, Rect& window, TermCriteria criteria)¶
The function implements the CAMSHIFT object tracking algrorithm Bradski98. First, it
finds an object center using meanShift and then adjust the window size and finds the optimal
rotation. The function returns the rotated rectangle structure that includes the object position,
size and the orientation. The next position of the search window can be obtained with
RotatedRect::boundingRect().
meanShift¶
int meanShift(const Mat& probImage, Rect& window, TermCriteria criteria)¶
The function implements iterative object search algorithm. It takes the object back
projection on input and the initial position. The mass center in window of the back projection
image is computed and the search window center shifts to the mass center. The procedure is
repeated until the specified number of iterations criteria.maxCount is done or until the
window center shifts by less than criteria.epsilon. The algorithm is used inside
CamShift and, unlike CamShift, the search window size or orientation do not change during
the search. You can simply pass the output of calcBackProject to this function, but better
results can be obtained if you pre-filter the back projection and remove the noise (e.g. by
retrieving connected components with findContours, throwing away contours with small
area (contourArea) and rendering the remaining contours with drawContours)
KalmanFilter¶
Kalman filter class
class KalmanFilter
{
public:
KalmanFilter();newline
KalmanFilter(int dynamParams, int measureParams, int
controlParams=0);newline
void init(int dynamParams, int measureParams, int controlParams=0);newline
// predicts statePre from statePost
const Mat& predict(const Mat& control=Mat());newline
// corrects statePre based on the input measurement vector
// and stores the result to statePost.
const Mat& correct(const Mat& measurement);newline
Object Detection¶
FeatureEvaluator¶
Base class for computing feature values in cascade classifiers
class FeatureEvaluator
{
public:
// feature type
enum { HAAR = 0, LBP = 1 };
virtual ~FeatureEvaluator();
// reads parameters of the features from a FileStorage node
virtual bool read(const FileNode& node);
// returns a full copy of the feature evaluator
virtual Ptr<FeatureEvaluator> clone() const;
// returns the feature type (HAAR or LBP for now)
virtual int getFeatureType() const;
CascadeClassifier¶
The cascade classifier class for object detection
class CascadeClassifier
{
public:
enum { BOOST = 0 };
// default constructor
CascadeClassifier();
// load the classifier from file
CascadeClassifier(const string& filename);
// the destructor
~CascadeClassifier();
bool is_stump_based;
int stageType;
int featureType;
int ncategories;
Size origWinSize;
Ptr<FeatureEvaluator> feval;
Ptr<CvHaarClassifierCascade> oldCascade;
};
groupRectangles¶
void groupRectangles(vector<Rect>& rectList, int groupThreshold, double eps=0.2)¶
The function is a wrapper for a generic function partition. It clusters all the input rectangles
using the rectangle equivalence criteria, that combines rectangles that have similar sizes and
similar locations (the similarity is defined by eps). When eps=0, no clustering is done at all.
If , all the rectangles will be put in one cluster. Then, the small clusters,
containing less than or equal to groupThreshold rectangles, will be rejected. In each other
cluster the average rectangle will be computed and put into the output rectangle list.
matchTemplate¶
void matchTemplate(const Mat& image, const Mat& templ, Mat& result, int method)¶
The function slides through image, compares the overlapped patches of size against
templ using the specified method and stores the comparison results to result. Here are the
formulas for the available comparison methods ( denotes image, template, result).
The summation is done over template and/or the image patch:
• method=CV_TM_SQDIFF *
• method=CV_TM_SQDIFF_NORMED *
• method=CV_TM_CCORR *
• method=CV_TM_CCORR_NORMED *
• method=CV_TM_CCOEFF *
where
• method=CV_TM_CCOEFF_NORMED *
After the function finishes the comparison, the best matches can be found as global
minimums (when CV_TM_SQDIFF was used) or maximums (when CV_TM_CCORR or
CV_TM_CCOEFF was used) using the minMaxLoc function. In the case of a color image,
template summation in the numerator and each sum in the denominator is done over all of
the channels (and separate mean values are used for each channel). That is, the function can
take a color template and a color image; the result will still be a single-channel image, which
is easier to analyze.
or
Where are the coordinates of a 3D point in the world coordinate space, are the
coordinates of the projection point in pixels. is called a camera matrix, or a matrix of intrinsic
parameters. is a principal point (that is usually at the image center), and are the
focal lengths expressed in pixel-related units. Thus, if an image from camera is scaled by some
factor, all of these parameters should be scaled (multiplied/divided, respectively) by the same
factor. The matrix of intrinsic parameters does not depend on the scene viewed and, once estimated,
can be re-used (as long as the focal length is fixed (in case of zoom lens)). The joint rotation-
translation matrix is called a matrix of extrinsic parameters. It is used to describe the camera
motion around a static scene, or vice versa, rigid motion of an object in front of still camera. That is,
translates coordinates of a point to some coordinate system, fixed with respect to the
camera. The transformation above is equivalent to the following (when ):
Real lenses usually have some distortion, mostly radial distorion and slight tangential distortion. So,
the above model is extended as:
vector. That is, if the vector contains 4 elements, it means that . The distortion coefficients
do not depend on the scene viewed, thus they also belong to the intrinsic camera parameters. And
they remain the same regardless of the captured image resolution. That is, if, for example, a camera
has been calibrated on images of resolution, absolutely the same distortion coefficients
can be used for images of resolution from the same camera (while , , and
need to be scaled appropriately).
• Project 3D points to the image plane given intrinsic and extrinsic parameters
• Compute extrinsic parameters given intrinsic parameters, a few 3D points and their
projections.
• Estimate intrinsic and extrinsic camera parameters from several views of a known
calibration pattern (i.e. every view is described by several 3D-2D point
correspodences).
• Estimate the relative position and orientation of the stereo camera “heads” and
compute the rectification transformation that makes the camera optical axes parallel.
calibrateCamera¶
double calibrateCamera(const vector<vector<Point3f> >& objectPoints, const
vector<vector<Point2f> >& imagePoints, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs,
vector<Mat>& rvecs, vector<Mat>& tvecs, int flags=0)¶
Finds the camera intrinsic and extrinsic parameters from several views of a calibration
pattern.
o CV_CALIB_USE_INTRINSIC_GUESS - cameraMatrix
contains the valid initial values of fx, fy, cx, cy that are
optimized further. Otherwise, (cx, cy) is initially set to the
image center (imageSize is used here), and focal distances are
computed in some least-squares fashion. Note, that if intrinsic
parameters are known, there is no need to use this function just
to estimate the extrinsic parameters. Use solvePnP instead.
o CV_CALIB_FIX_PRINCIPAL_POINT - The principal point
is not changed during the global optimization, it stays at the
center or at the other location specified when
CV_CALIB_USE_INTRINSIC_GUESS is set too.
o CV_CALIB_FIX_ASPECT_RATIO - The functions
considers only fy as a free parameter, the ratio fx/fy stays the
same as in the input cameraMatrix. When
CV_CALIB_USE_INTRINSIC_GUESS is not set, the actual input
values of fx and fy are ignored, only their ratio is computed
and used further.
o CV_CALIB_ZERO_TANGENT_DIST - Tangential
distortion coefficients will be set to zeros and stay
zero.
The function estimates the intrinsic camera parameters and extrinsic parameters for each of
the views. The coordinates of 3D object points and their correspondent 2D projections in
each view must be specified. That may be achieved by using an object with known geometry
and easily detectable feature points. Such an object is called a calibration rig or calibration
pattern, and OpenCV has built-in support for a chessboard as a calibration rig (see
findChessboardCorners). Currently, initialization of intrinsic parameters (when
CV_CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration
patterns (where z-coordinates of the object points must be all 0’s). 3D calibration rigs can
also be used as long as initial cameraMatrix is provided.
• First, it computes the initial intrinsic parameters (the option only available for planar
calibration patterns) or reads them from the input parameters. The distortion
coefficients are all set to zeros initially (unless some of CV_CALIB_FIX_K? are
specified).
• The the initial camera pose is estimated as if the intrinsic parameters have been
already known. This is done using solvePnP
• After that the global Levenberg-Marquardt optimization algorithm is run to minimize
the reprojection error, i.e. the total sum of squared distances between the observed
feature points imagePoints and the projected (using the current estimates for
camera parameters and the poses) object points objectPoints; see projectPoints.
calibrationMatrixValues¶
void calibrationMatrixValues(const Mat& cameraMatrix, Size imageSize, double
apertureWidth, double apertureHeight, double& fovx, double& fovy, double& focalLength,
Point2d& principalPoint, double& aspectRatio)¶
The function computes various useful camera characteristics from the previously estimated
camera matrix.
composeRT¶
void composeRT(const Mat& rvec1, const Mat& tvec1, const Mat& rvec2, const Mat& tvec2, Mat&
rvec3, Mat& tvec3)¶
void composeRT(const Mat& rvec1, const Mat& tvec1, const Mat& rvec2, const Mat& tvec2, Mat&
rvec3, Mat& tvec3, Mat& dr3dr1, Mat& dr3dt1, Mat& dr3dr2, Mat& dr3dt2, Mat& dt3dr1, Mat&
dt3dt1, Mat& dt3dr2, Mat& dt3dt2)
Also, the functions can compute the derivatives of the output vectors w.r.t the input vectors
(see matMulDeriv). The functions are used inside stereoCalibrate but can also be used in
your own code where Levenberg-Marquardt or another gradient-based solver is used to
optimize a function that contains matrix multiplication.
computeCorrespondEpilines¶
void computeCorrespondEpilines(const Mat& points, int whichImage, const Mat& F,
vector<Vec3f>& lines)¶
For points in one image of a stereo pair, computes the corresponding epilines in the other
image.
For every point in one of the two images of a stereo-pair the function finds the equation of
the corresponding epipolar line in the other image.
From the fundamental matrix definition (see findFundamentalMat), line in the second
image for the point in the first image (i.e. when whichImage=1) is computed as:
Line coefficients are defined up to a scale. They are normalized, such that .
convertPointsHomogeneous¶
void convertPointsHomogeneous(const Mat& src, vector<Point3f>& dst)¶
void convertPointsHomogeneous(const Mat& src, vector<Point2f>& dst)
decomposeProjectionMatrix¶
void decomposeProjectionMatrix(const Mat& projMatrix, Mat& cameraMatrix, Mat&
rotMatrix, Mat& transVect)¶
void decomposeProjectionMatrix(const Mat& projMatrix, Mat& cameraMatrix, Mat&
rotMatrix, Mat& transVect, Mat& rotMatrixX, Mat& rotMatrixY, Mat& rotMatrixZ, Vec3d&
eulerAngles)
Decomposes the projection matrix into a rotation matrix and a camera matrix.
It optionally returns three rotation matrices, one for each axis, and the three Euler angles that
could be used in OpenGL.
drawChessboardCorners¶
void drawChessboardCorners(Mat& image, Size patternSize, const Mat& corners, bool
patternWasFound)¶
The function draws the individual chessboard corners detected as red circles if the board was
not found or as colored corners connected with lines if the board was found.
findChessboardCorners¶
bool findChessboardCorners(const Mat& image, Size patternSize, vector<Point2f>& corners, int
flags=CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE)¶
The function attempts to determine whether the input image is a view of the chessboard
pattern and locate the internal chessboard corners. The function returns a non-zero value if
all of the corners have been found and they have been placed in a certain order (row by row,
left to right in every row), otherwise, if the function fails to find all the corners or reorder
them, it returns 0. For example, a regular chessboard has 8 x 8 squares and 7 x 7 internal
corners, that is, points, where the black squares touch each other. The coordinates detected
are approximate, and to determine their position more accurately, the user may use the
function cornerSubPix.
Note: the function requires some white space (like a square-thick border, the wider the
better) around the board to make the detection more robust in various environment
(otherwise if there is no border and the background is dark, the outer black squares could not
be segmented properly and so the square grouping and ordering algorithm will fail).
solvePnP¶
void solvePnP(const Mat& objectPoints, const Mat& imagePoints, const Mat& cameraMatrix,
const Mat& distCoeffs, Mat& rvec, Mat& tvec, bool useExtrinsicGuess=false)¶
The function estimates the object pose given a set of object points, their corresponding
image projections, as well as the camera matrix and the distortion coefficients. This function
finds such a pose that minimizes reprojection error, i.e. the sum of squared distances
between the observed projections imagePoints and the projected (using projectPoints)
objectPoints.
findFundamentalMat¶
Mat findFundamentalMat(const Mat& points1, const Mat& points2, vector<uchar>& status, int
method=FM_RANSAC, double param1=3., double param2=0.99)¶
Mat findFundamentalMat(const Mat& points1, const Mat& points2, int method=FM_RANSAC,
double param1=3., double param2=0.99)
Calculates the fundamental matrix from the corresponding points in two images.
• points1 – Array of N points from the first image.. The point coordinates
Parameters:
should be floating-point (single or double precision)
• points2 – Array of the second image points of the same size and format
as points1
• method –
where is fundamental matrix, and are corresponding points in the first and the
second images, respectively.
The function calculates the fundamental matrix using one of four methods listed above and
returns the found fundamental matrix. Normally just 1 matrix is found, but in the case of 7-
point algorithm the function may return up to 3 solutions ( matrix that stores all 3
matrices sequentially).
findHomography¶
Mat findHomography(const Mat& srcPoints, const Mat& dstPoints, Mat& status, int method=0,
double ransacReprojThreshold=0)¶
Mat findHomography(const Mat& srcPoints, const Mat& dstPoints, vector<uchar>& status, int
method=0, double ransacReprojThreshold=0)
Mat findHomography(const Mat& srcPoints, const Mat& dstPoints, int method=0, double
ransacReprojThreshold=0)
param srcPoints:
Coordinates of the points in the original plane, a matrix of type CV_32FC2 or a
vector<Point2f>.
param dstPoints:
Coordinates of the points in the target plane, a matrix of type CV_32FC2 or a
vector<Point2f>.
The method used to computed homography matrix; one of the following:
param
• 0 - a regular method using all the points
metho
• CV_RANSAC - RANSAC-based robust method
d:
• CV_LMEDS - Least-Median robust method
param ransacReprojThreshold:
The maximum allowed reprojection error to treat a point pair as an inlier (used in the
RANSAC method only). That is, if
then the point is considered an outlier. If srcPoints and dstPoints are measured in
pixels, it usually makes sense to set this parameter somewhere in the range 1 to 10.
param The optional output mask set by a robust method (CV_RANSAC or CV_LMEDS).
status: Note that the input mask values are ignored.
The functions find and return the perspective transformation between the source and the
destination planes:
However, if not all of the point pairs ( , ) fit the rigid perspective
transformation (i.e. there are some outliers), this initial estimate will be poor. In this case
one can use one of the 2 robust methods. Both methods, RANSAC and LMeDS, try many
different random subsets of the corresponding point pairs (of 4 pairs each), estimate the
homography matrix using this subset and a simple least-square algorithm and then compute
the quality/goodness of the computed homography (which is the number of inliers for
RANSAC or the median re-projection error for LMeDs). The best subset is then used to
produce the initial estimate of the homography matrix and the mask of inliers/outliers.
Regardless of the method, robust or not, the computed homography matrix is refined further
(using inliers only in the case of a robust method) with the Levenberg-Marquardt method in
order to reduce the re-projection error even more.
The method RANSAC can handle practically any ratio of outliers, but it needs the threshold to
distinguish inliers from outliers. The method LMeDS does not need any threshold, but it
works correctly only when there are more than 50% of inliers. Finally, if you are sure in the
computed features, where can be only some small noise present, but no outliers, the default
method could be the best choice.
The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is
determined up to a scale, thus it is normalized so that .
getDefaultNewCameraMatrix¶
Mat getDefaultNewCameraMatrix(const Mat& cameraMatrix, Size imgSize=Size(), bool
centerPrincipalPoint=false)¶
The function returns the camera matrix that is either an exact copy of the input
cameraMatrix (when centerPrinicipalPoint=false), or the modified one (when
``centerPrincipalPoint``=true).
getOptimalNewCameraMatrix¶
Mat getOptimalNewCameraMatrix(const Mat& cameraMatrix, const Mat& distCoeffs, Size
imageSize, double alpha, Size newImgSize=Size(), Rect* validPixROI=0)¶
Returns the new camera matrix based on the free scaling parameter
The function computes and returns the optimal new camera matrix based on the free scaling
parameter. By varying this parameter the user may retrieve only sensible pixels alpha=0,
keep all the original image pixels if there is valuable information in the corners alpha=1, or
get something in between. When alpha>0, the undistortion result will likely have some
black pixels corresponding to “virtual” pixels outside of the captured distorted image. The
original camera matrix, distortion coefficients, the computed new camera matrix and the
bgroup({newImageSize}) should be passed to initUndistortRectifyMap to produce the maps
for remap.
initCameraMatrix2D¶
Mat initCameraMatrix2D(const vector<vector<Point3f> >& objectPoints, const
vector<vector<Point2f> >& imagePoints, Size imageSize, double aspectRatio=1.)¶
Finds the initial camera matrix from the 3D-2D point correspondences
The function estimates and returns the initial camera matrix for camera calibration process.
Currently, the function only supports planar calibration patterns, i.e. patterns where each
object point has z-coordinate =0.
initUndistortRectifyMap¶
void initUndistortRectifyMap(const Mat& cameraMatrix, const Mat& distCoeffs, const Mat&
R, const Mat& newCameraMatrix, Size size, int m1type, Mat& map1, Mat& map2)¶
The function computes the joint undistortion+rectification transformation and represents the
result in the form of maps for remap. The undistorted image will look like the original, as if
it was captured with a camera with camera matrix =newCameraMatrix and zero distortion.
In the case of monocular camera newCameraMatrix is usually equal to cameraMatrix, or it
can be computed by getOptimalNewCameraMatrix for a better control over scaling. In the
case of stereo camera newCameraMatrix is normally set to P1 or P2 computed by
stereoRectify.
Also, this new camera will be oriented differently in the coordinate space, according to R.
That, for example, helps to align two heads of a stereo camera so that the epipolar lines on
both images become horizontal and have the same y- coordinate (in the case of horizontally
aligned stereo camera).
The function actually builds the maps for the inverse mapping algorithm that is used by
remap. That is, for each pixel in the destination (corrected and rectified) image the
function computes the corresponding coordinates in the source image (i.e. in the original
image from camera). The process is the following:
In the case of a stereo camera this function is called twice, once for each camera head, after
stereoRectify, which in its turn is called after stereoCalibrate. But if the stereo camera was
not calibrated, it is still possible to compute the rectification transformations directly from
the fundamental matrix using stereoRectifyUncalibrated. For each camera the function
computes homography H as the rectification transformation in pixel domain, not a rotation
matrix R in 3D space. The R can be computed from H as
matMulDeriv¶
void matMulDeriv(const Mat& A, const Mat& B, Mat& dABdA, Mat& dABdB)¶
Computes partial derivatives of the matrix product w.r.t each multiplied matrix
projectPoints¶
void projectPoints(const Mat& objectPoints, const Mat& rvec, const Mat& tvec, const Mat&
cameraMatrix, const Mat& distCoeffs, vector<Point2f>& imagePoints)¶
void projectPoints(const Mat& objectPoints, const Mat& rvec, const Mat& tvec, const Mat&
cameraMatrix, const Mat& distCoeffs, vector<Point2f>& imagePoints, Mat& dpdrot, Mat& dpdt,
Mat& dpdf, Mat& dpdc, Mat& dpddist, double aspectRatio=0)
The function computes projections of 3D points to the image plane given intrinsic and
extrinsic camera parameters. Optionally, the function computes jacobians - matrices of
partial derivatives of image points coordinates (as functions of all the input parameters) with
respect to the particular parameters, intrinsic and/or extrinsic. The jacobians are used during
the global optimization in calibrateCamera, solvePnP and stereoCalibrate. The function
itself can also used to compute re-projection error given the current intrinsic and extrinsic
parameters.
reprojectImageTo3D¶
void reprojectImageTo3D(const Mat& disparity, Mat& _3dImage, const Mat& Q, bool
handleMissingValues=false)¶
The matrix Q can be arbitrary matrix, e.g. the one computed by stereoRectify. To
reproject a sparse set of points bgroup({(x,y,d),...}) to 3D space, use perspectiveTransform.
RQDecomp3x3¶
void RQDecomp3x3(const Mat& M, Mat& R, Mat& Q)¶
Vec3d RQDecomp3x3(const Mat& M, Mat& R, Mat& Q, Mat& Qx, Mat& Qy, Mat& Qz)
The function computes a RQ decomposition using the given rotations. This function is used
in decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix
into a camera and a rotation matrix.
It optionally returns three rotation matrices, one for each axis, and the three Euler angles (as
the return value) that could be used in OpenGL.
Rodrigues¶
void Rodrigues(const Mat& src, Mat& dst)¶
void Rodrigues(const Mat& src, Mat& dst, Mat& jacobian)
• src – The input rotation vector (3x1 or 1x3) or rotation matrix (3x3)
• dst – The output rotation matrix (3x3) or rotation vector (3x1 or 1x3),
respectively
Parameters: • jacobian – Optional output Jacobian matrix, 3x9 or 9x3 - partial
derivatives of the output array components with respect to the input
array components
StereoBM¶
The class for computing stereo correspondence using block matching algorithm.
// Block matching stereo correspondence algorithm\par
class StereoBM
{
enum { NORMALIZED_RESPONSE = CV_STEREO_BM_NORMALIZED_RESPONSE,
BASIC_PRESET=CV_STEREO_BM_BASIC,
FISH_EYE_PRESET=CV_STEREO_BM_FISH_EYE,
NARROW_PRESET=CV_STEREO_BM_NARROW };
StereoBM();
// the preset is one of ..._PRESET above.
// ndisparities is the size of disparity range,
// in which the optimal disparity at each pixel is searched for.
// SADWindowSize is the size of averaging window used to match pixel blocks
// (larger values mean better robustness to noise, but yield blurry
disparity maps)
StereoBM(int preset, int ndisparities=0, int SADWindowSize=21);
// separate initialization function
void init(int preset, int ndisparities=0, int SADWindowSize=21);
// computes the disparity for the two rectified 8-bit single-channel images.
// the disparity will be 16-bit singed image of the same size as left.
void operator()( const Mat& left, const Mat& right, Mat& disparity );
Ptr<CvStereoBMState> state;
};
stereoCalibrate¶
double stereoCalibrate(const vector<vector<Point3f> >& objectPoints, const
vector<vector<Point2f> >& imagePoints1, const vector<vector<Point2f> >& imagePoints2, Mat&
cameraMatrix1, Mat& distCoeffs1, Mat& cameraMatrix2, Mat& distCoeffs2, Size imageSize,
Mat& R, Mat& T, Mat& E, Mat& F, TermCriteria criteria =
TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6), int
flags=CALIB_FIX_INTRINSIC)¶
The function estimates transformation between the 2 cameras making a stereo pair. If we
have a stereo camera, where the relative position and orientatation of the 2 cameras is fixed,
and if we computed poses of an object relative to the fist camera and to the second camera,
(R1, T1) and (R2, T2), respectively (that can be done with solvePnP), obviously, those
poses will relate to each other, i.e. given ( , ) it should be possible to compute ( , )
- we only need to know the position and orientation of the 2nd camera relative to the 1st
camera. That’s what the described function does. It computes ( , ) such that:
Besides the stereo-related information, the function can also perform full calibration of each
of the 2 cameras. However, because of the high dimensionality of the parameter space and
noise in the input data the function can diverge from the correct solution. Thus, if intrinsic
parameters can be estimated with high accuracy for each of the cameras individually (e.g.
using calibrateCamera), it is recommended to do so and then pass
CV_CALIB_FIX_INTRINSIC flag to the function along with the computed intrinsic
parameters. Otherwise, if all the parameters are estimated at once, it makes sense to restrict
some parameters, e.g. pass CV_CALIB_SAME_FOCAL_LENGTH and
CV_CALIB_ZERO_TANGENT_DIST flags, which are usually reasonable assumptions.
Similarly to calibrateCamera, the function minimizes the total re-projection error for all the
points in all the available views from both cameras. The function returns the final value of
the re-projection error.
stereoRectify¶
void stereoRectify(const Mat& cameraMatrix1, const Mat& distCoeffs1, const Mat&
cameraMatrix2, const Mat& distCoeffs2, Size imageSize, const Mat& R, const Mat& T, Mat& R1,
Mat& R2, Mat& P1, Mat& P2, Mat& Q, int flags=CALIB_ZERO_DISPARITY)¶
void stereoRectify(const Mat& cameraMatrix1, const Mat& distCoeffs1, const Mat&
cameraMatrix2, const Mat& distCoeffs2, Size imageSize, const Mat& R, const Mat& T, Mat& R1,
Mat& R2, Mat& P1, Mat& P2, Mat& Q, double alpha, Size newImageSize=Size(), Rect* roi1=0,
Rect* roi2=0, int flags=CALIB_ZERO_DISPARITY)
Computes rectification transforms for each head of a calibrated stereo camera.
.
• distCoeffs1, distCoeffs2 – The input distortion coefficients for each
camera,
• imageSize – Size of the image used for stereo calibration.
• R – The rotation matrix between the 1st and the 2nd cameras’
coordinate systems.
• T – The translation vector between the cameras’ coordinate systems.
• R1, R2 – The output rectification transforms (rotation matrices)
for the first and the second cameras, respectively.
• P1, P2 – The output projection matrices in the new (rectified)
coordinate systems.
• Q – The output disparity-to-depth mapping matrix, see
reprojectImageTo3D.
• flags – The operation flags; may be 0 or CV_CALIB_ZERO_DISPARITY.
If the flag is set, the function makes the principal points of each camera
have the same pixel coordinates in the rectified views. And if the flag
Parameters: is not set, the function may still shift the images in horizontal or
vertical direction (depending on the orientation of epipolar lines) in
order to maximize the useful image area.
• alpha – The free scaling parameter. If it is -1 or absent, the functions
performs some default scaling. Otherwise the parameter should be
between 0 and 1. alpha=0 means that the rectified images will be
zoomed and shifted so that only valid pixels are visible (i.e. there will
be no black areas after rectification). alpha=1 means that the rectified
image will be decimated and shifted so that all the pixels from the
original images from the cameras are retained in the rectified images,
i.e. no source image pixels are lost. Obviously, any intermediate value
yields some intermediate result between those two extreme cases.
• newImageSize – The new image resolution after rectification. The
same size should be passed to initUndistortRectifyMap, see the
stereo_calib.cpp sample in OpenCV samples directory. By default,
i.e. when (0,0) is passed, it is set to the original imageSize. Setting it
to larger value can help you to preserve details in the original image,
especially when there is big radial distortion.
• roi1, roi2 – The optional output rectangles inside the rectified images
where all the pixels are valid. If alpha=0, the ROIs will cover the
whole images, otherwise they likely be smaller, see the picture below
The function computes the rotation matrices for each camera that (virtually) make both
camera image planes the same plane. Consequently, that makes all the epipolar lines parallel
and thus simplifies the dense stereo correspondence problem. On input the function takes the
matrices computed by stereoCalibrate and on output it gives 2 rotation matrices and also 2
projection matrices in the new coordinates. The 2 cases are distinguished by the function
are:
• Horizontal stereo, when 1st and 2nd camera views are shifted relative to each other
mainly along the x axis (with possible small vertical shift). Then in the rectified
images the corresponding epipolar lines in left and right cameras will be horizontal
and have the same y-coordinate. P1 and P2 will look as:
• Vertical stereo, when 1st and 2nd camera views are shifted relative to each other
mainly in vertical direction (and probably a bit in the horizontal direction too). Then
the epipolar lines in the rectified images will be vertical and have the same x
coordinate. P2 and P2 will look as:
As you can see, the first 3 columns of P1 and P2 will effectively be the new “rectified”
camera matrices. The matrices, together with R1 and R2, can then be passed to
initUndistortRectifyMap to initialize the rectification map for each camera.
Below is the screenshot from stereo_calib.cpp sample. Some red horizontal lines, as you
can see, pass through the corresponding image regions, i.e. the images are well rectified
(which is what most stereo correspondence algorithms rely on). The green rectangles are
roi1 and roi2 - indeed, their interior are all valid pixels.
stereoRectifyUncalibrated¶
bool stereoRectifyUncalibrated(const Mat& points1, const Mat& points2, const Mat& F, Size
imgSize, Mat& H1, Mat& H2, double threshold=5)¶
Note that while the algorithm does not need to know the intrinsic parameters of the cameras,
it heavily depends on the epipolar geometry. Therefore, if the camera lenses have significant
distortion, it would better be corrected before computing the fundamental matrix and calling
this function. For example, distortion coefficients can be estimated for each head of stereo
camera separately by using calibrateCamera and then the images can be corrected using
undistort, or just the point coordinates can be corrected with undistortPoints.
undistort¶
void undistort(const Mat& src, Mat& dst, const Mat& cameraMatrix, const Mat& distCoeffs,
const Mat& newCameraMatrix=Mat())
The function transforms the image to compensate radial and tangential lens distortion.
Those pixels in the destination image, for which there is no correspondent pixels in the
source image, are filled with 0’s (black color).
The particular subset of the source image that will be visible in the corrected image can be
regulated by newCameraMatrix. You can use getOptimalNewCameraMatrix to compute the
appropriate newCameraMatrix, depending on your requirements.
The camera matrix and the distortion parameters can be determined using calibrateCamera.
If the resolution of images is different from the used at the calibration stage, and
need to be scaled accordingly, while the distortion coefficients remain the same.
undistortPoints¶
void undistortPoints(const Mat& src, vector<Point2f>& dst, const Mat& cameraMatrix, const
Mat& distCoeffs, const Mat& R=Mat(), const Mat& P=Mat())¶
void undistortPoints(const Mat& src, Mat& dst, const Mat& cameraMatrix, const Mat&
distCoeffs, const Mat& R=Mat(), const Mat& P=Mat())
Computes the ideal point coordinates from the observed point coordinates.
where undistort() is approximate iterative algorithm that estimates the normalized original
point coordinates out of the normalized distorted point coordinates (“normalized” means
that the coordinates do not depend on the camera matrix).
The function can be used both for a stereo camera head or for monocular camera (when R is
empty).
User Interface¶
createTrackbar¶
int createTrackbar(const string& trackbarname, const string& winname, int* value, int count,
TrackbarCallback onChange CV_DEFAULT(0), void* userdata CV_DEFAULT(0))¶
The function createTrackbar creates a trackbar (a.k.a. slider or range control) with the
specified name and range, assigns a variable value to be syncronized with trackbar position
and specifies a callback function onChange to be called on the trackbar position change. The
created trackbar is displayed on the top of the given window.
getTrackbarPos¶
int getTrackbarPos(const string& trackbarname, const string& winname)¶
The function imshow displays the image in the specified window. If the window was created
with the CV_WINDOW_AUTOSIZE flag then the image is shown with its original size, otherwise
the image is scaled to fit in the window. The function may scale the image, depending on its
depth:
namedWindow¶
void namedWindow(const string& winname, int flags)¶
Creates a window.
• name – Name of the window in the window caption that may be used
as a window identifier.
• flags – Flags of the window. Currently the only supported flag is
Parameters: CV_WINDOW_AUTOSIZE. If this is set, the window size is automatically
adjusted to fit the displayed image (see imshow), and the user can not
change the window size manually.
The function namedWindow creates a window which can be used as a placeholder for images
and trackbars. Created windows are referred to by their names.
If a window with the same name already exists, the function does nothing.
setTrackbarPos¶
void setTrackbarPos(const string& trackbarname, const string& winname, int pos)¶
The function sets the position of the specified trackbar in the specified window.
waitKey¶
int waitKey(int delay=0)¶
Parameter: delay – Delay in milliseconds. 0 is the special value that means “forever”
The function waitKey waits for key event infinitely (when ) or for delay
milliseconds, when it’s positive. Returns the code of the pressed key or -1 if no key was
pressed before the specified time had elapsed.
Note: This function is the only method in HighGUI that can fetch and handle events, so it
needs to be called periodically for normal event processing, unless HighGUI is used within
some environment that takes care of event processing.
User Interface¶
createTrackbar¶
int createTrackbar(const string& trackbarname, const string& winname, int* value, int count,
TrackbarCallback onChange CV_DEFAULT(0), void* userdata CV_DEFAULT(0))¶
getTrackbarPos¶
int getTrackbarPos(const string& trackbarname, const string& winname)¶
imshow¶
void imshow(const string& winname, const Mat& image)
The function imshow displays the image in the specified window. If the window was created
with the CV_WINDOW_AUTOSIZE flag then the image is shown with its original size, otherwise
the image is scaled to fit in the window. The function may scale the image, depending on its
depth:
namedWindow¶
void namedWindow(const string& winname, int flags)¶
Creates a window.
• name – Name of the window in the window caption that may be used
as a window identifier.
Parameters:
• flags – Flags of the window. Currently the only supported flag is
CV_WINDOW_AUTOSIZE. If this is set, the window size is automatically
adjusted to fit the displayed image (see imshow), and the user can not
change the window size manually.
The function namedWindow creates a window which can be used as a placeholder for images
and trackbars. Created windows are referred to by their names.
If a window with the same name already exists, the function does nothing.
setTrackbarPos¶
void setTrackbarPos(const string& trackbarname, const string& winname, int pos)¶
The function sets the position of the specified trackbar in the specified window.
waitKey¶
int waitKey(int delay=0)¶
Parameter: delay – Delay in milliseconds. 0 is the special value that means “forever”
The function waitKey waits for key event infinitely (when ) or for delay
milliseconds, when it’s positive. Returns the code of the pressed key or -1 if no key was
pressed before the specified time had elapsed.
Note: This function is the only method in HighGUI that can fetch and handle events, so it
needs to be called periodically for normal event processing, unless HighGUI is used within
some environment that takes care of event processing.
Statistical Models¶
CvStatModel¶
Base class for the statistical models in ML.
class CvStatModel
{
public:
/* CvStatModel(); */
/* CvStatModel( const CvMat* train_data ... ); */
virtual ~CvStatModel();
/* virtual bool train( const CvMat* train_data, [int tflag,] ..., const
CvMat* responses, ...,
[const CvMat* var_idx,] ..., [const CvMat* sample_idx,] ...
[const CvMat* var_type,] ..., [const CvMat* missing_mask,]
<misc_training_alg_params> ... )=0;
*/
virtual void save( const char* filename, const char* name=0 )=0;
virtual void load( const char* filename, const char* name=0 )=0;
In this declaration some methods are commented off. Actually, these are methods for which there is
no unified API (with the exception of the default constructor), however, there are many similarities
in the syntax and semantics that are briefly described below in this section, as if they are a part of
the base class.
CvStatModel::CvStatModel¶
CvStatModel::CvStatModel()¶
Default constructor.
Each statistical model class in ML has a default constructor without parameters. This
constructor is useful for 2-stage model construction, when the default constructor is
followed by train() or load().
CvStatModel::CvStatModel(...)¶
CvStatModel::CvStatModel(const CvMat* train_data ...)
Training constructor.
Most ML classes provide single-step construct and train constructors. This constructor is
equivalent to the default constructor, followed by the train() method with the parameters
that are passed to the constructor.
CvStatModel::CvStatModel¶
CvStatModel::~ CvStatModel()¶
Virtual destructor.
The destructor of the base class is declared as virtual, so it is safe to write the following
code:
CvStatModel* model;
if( use\_svm )
model = new CvSVM(... /* SVM params */);
else
model = new CvDTree(... /* Decision tree params */);
...
delete model;
Normally, the destructor of each derived class does nothing, but in this instance it calls the
overridden method clear() that deallocates all the memory.
CvStatModel::clear¶
void CvStatModel::clear()¶
The method clear does the same job as the destructor; it deallocates all the memory
occupied by the class members. But the object itself is not destructed, and can be reused
further. This method is called from the destructor, from the train methods of the derived
classes, from the methods load(), read() or even explicitly by the user.
CvStatModel::save¶
void CvStatModel::save(const char* filename, const char* name=0)¶
The method save stores the complete model state to the specified XML or YAML file with
the specified name or default name (that depends on the particular class). Data
persistence functionality from CxCore is used.
CvStatModel::load¶
void CvStatModel::load(const char* filename, const char* name=0)¶
The method load loads the complete model state with the specified name (or default model-
dependent name) from the specified XML or YAML file. The previous model state is
cleared by clear().
Note that the method is virtual, so any model can be loaded using this virtual method.
However, unlike the C types of OpenCV that can be loaded using the generic
crossbgroup({cvLoad}), here the model type must be known, because an empty model must
be constructed beforehand. This limitation will be removed in the later ML versions.
CvStatModel::write¶
void CvStatModel::write(CvFileStorage* storage, const char* name)¶
The method write stores the complete model state to the file storage with the specified
name or default name (that depends on the particular class). The method is called by
save().
CvStatModel::read¶
void CvStatMode::read(CvFileStorage* storage, CvFileNode* node)¶
The method read restores the complete model state from the specified node of the file
storage. The node must be located by the user using the function GetFileNodeByName.
CvStatModel::train¶
bool CvStatMode::train(const CvMat* train_data, [int tflag, ] ..., const CvMat* responses, ...,
[const CvMat* var_idx, ] ..., [const CvMat* sample_idx, ] ... [const CvMat* var_type, ] ..., [const
CvMat* missing_mask, ] <misc_training_alg_params> ...)¶
The method trains the statistical model using a set of input feature vectors and the
corresponding output values (responses). Both input and output vectors/values are passed as
matrices. By default the input feature vectors are stored as train_data rows, i.e. all the
components (features) of a training vector are stored continuously. However, some
algorithms can handle the transposed representation, when all values of each particular
feature (component/input variable) over the whole input set are stored continuously. If both
layouts are supported, the method includes tflag parameter that specifies the orientation:
For classification problems the responses are discrete class labels; for regression problems
the responses are values of the function to be approximated. Some algorithms can deal only
with classification problems, some - only with regression problems, and some can deal with
both problems. In the latter case the type of output variable is either passed as separate
parameter, or as a last element of var_type vector:
• CV_VAR_CATEGORICAL means that the output values are discrete class labels,
• CV_VAR_ORDERED(=CV_VAR_NUMERICAL) means that the output values are ordered,
i.e. 2 different values can be compared as numbers, and this is a regression problem
The types of input variables can be also specified using var_type. Most algorithms can
handle only ordered input variables.
Many models in the ML may be trained on a selected feature subset, and/or on a selected
sample subset of the training set. To make it easier for the user, the method train usually
includes var_idx and sample_idx parameters. The former identifies variables (features) of
interest, and the latter identifies samples of interest. Both vectors are either integer
(CV_32SC1) vectors, i.e. lists of 0-based indices, or 8-bit (CV_8UC1) masks of active
variables/samples. The user may pass NULL pointers instead of either of the arguments,
meaning that all of the variables/samples are used for training.
Additionally some algorithms can handle missing measurements, that is when certain
features of certain training samples have unknown values (for example, they forgot to
measure a temperature of patient A on Monday). The parameter missing_mask, an 8-bit
matrix the same size as train_data, is used to mark the missed values (non-zero elements
of the mask).
Usually, the previous model state is cleared by clear() before running the training
procedure. However, some algorithms may optionally update the model state with the new
training data, instead of resetting it.
CvStatModel::predict¶
float CvStatMode::predict(const CvMat* sample[, <prediction_params>]) const¶
The method is used to predict the response for a new sample. In the case of classification the
method returns the class label, in the case of regression - the output function value. The
input sample must have as many components as the train_data passed to train contains.
If the var_idx parameter is passed to train, it is remembered and then is used to extract
only the necessary components from the input sample in the method predict.
The suffix “const” means that prediction does not affect the internal model state, so the
method can be safely called from within different threads.
[Fukunaga90] K. Fukunaga. Introduction to Statistical Pattern Recognition. second ed., New York:
Academic Press, 1990.
CvNormalBayesClassifier¶
Bayes classifier for normally distributed data.
CvNormalBayesClassifier::train¶
bool CvNormalBayesClassifier::train(const CvMat* _train_data, const CvMat* _responses,
const CvMat* _var_idx =0, const CvMat* _sample_idx=0, bool update=false)¶
The method trains the Normal Bayes classifier. It follows the conventions of the generic
train “method” with the following limitations: only CV_ROW_SAMPLE data layout is
supported; the input variables are all ordered; the output variable is categorical (i.e. elements
of _responses must be integer numbers, though the vector may have CV_32FC1 type), and
missing measurements are not supported.
In addition, there is an update flag that identifies whether the model should be trained from
scratch (update=false) or should be updated using the new training data (update=true).
CvNormalBayesClassifier::predict¶
float CvNormalBayesClassifier::predict(const CvMat* samples, CvMat* results=0) const¶
The method predict estimates the most probable classes for the input vectors. The input
vectors (one or more) are stored as rows of the matrix samples. In the case of multiple input
vectors, there should be one output vector results. The predicted class for a single input
vector is returned by the method.
K Nearest Neighbors¶
The algorithm caches all of the training samples, and predicts the response for a new sample by
analyzing a certain number (K) of the nearest neighbors of the sample (using voting, calculating
weighted sum etc.) The method is sometimes referred to as “learning by example”, because for
prediction it looks for the feature vector with a known response that is closest to the given vector.
CvKNearest¶
K Nearest Neighbors model.
CvKNearest();
virtual ~CvKNearest();
protected:
...
};
CvKNearest::train¶
bool CvKNearest::train(const CvMat* _train_data, const CvMat* _responses, const CvMat*
_sample_idx=0, bool is_regression=false, int _max_k=32, bool _update_base=false)¶
Trains the model.
The method trains the K-Nearest model. It follows the conventions of generic train
“method” with the following limitations: only CV_ROW_SAMPLE data layout is
supported, the input variables are all ordered, the output variables can be either categorical
(is_regression=false) or ordered (is_regression=true), variable subsets (var_idx)
and missing measurements are not supported.
The parameter _max_k specifies the number of maximum neighbors that may be passed to
the method find_nearest.
The parameter _update_base specifies whether the model is trained from scratch
(_update_base=false), or it is updated using the new training data (_update_base=true).
In the latter case the parameter _max_k must not be larger than the original value.
CvKNearest::find_nearest¶
float CvKNearest::find_nearest(const CvMat* _samples, int k, CvMat* results=0, const float**
neighbors=0, CvMat* neighbor_responses=0, CvMat* dist=0) const¶
For each input vector (which are the rows of the matrix _samples) the method finds the
nearest neighbor. In the case of regression, the predicted result will
be a mean value of the particular vector’s neighbor responses. In the case of classification
the class is determined by voting.
For custom classification/regression prediction, the method can optionally return pointers to
the neighbor vectors themselves (neighbors, an array of k*_samples->rows pointers),
their corresponding output values (neighbor_responses, a vector of k*_samples->rows
elements) and the distances from the input vectors to the neighbors (dist, also a vector of
k*_samples->rows elements).
For each input vector the neighbors are sorted by their distances to the vector.
If only a single input vector is passed, all output matrices are optional and the predicted
value is returned by the method.
// learn classifier
CvKNearest knn( trainData, trainClasses, 0, false, K );
CvMat* nearests = cvCreateMat( 1, K, CV_32FC1);
cvReleaseMat( &trainClasses );
cvReleaseMat( &trainData );
return 0;
}
The solution is optimal in a sense that the margin between the separating hyper-plane and the
nearest feature vectors from the both classes (in the case of 2-class classifier) is maximal. The
feature vectors that are the closest to the hyper-plane are called “support vectors”, meaning that the
position of other vectors does not affect the hyper-plane (the decision function).
There are a lot of good references on SVM. Here are only a few ones to start with.
CvSVM¶
Support Vector Machines.
CvSVM();
virtual ~CvSVM();
protected:
...
};
CvSVMParams¶
SVM training parameters.
struct CvSVMParams
{
CvSVMParams();
CvSVMParams( int _svm_type, int _kernel_type,
double _degree, double _gamma, double _coef0,
double _C, double _nu, double _p,
CvMat* _class_weights, CvTermCriteria _term_crit );
int svm_type;
int kernel_type;
double degree; // for poly
double gamma; // for poly/rbf/sigmoid
double coef0; // for poly/sigmoid
CvSVM::train¶
bool CvSVM::train(const CvMat* _train_data, const CvMat* _responses, const CvMat*
_var_idx=0, const CvMat* _sample_idx=0, CvSVMParams _params=CvSVMParams())¶
Trains SVM.
The method trains the SVM model. It follows the conventions of the generic train
“method” with the following limitations: only the CV_ROW_SAMPLE data layout is
supported, the input variables are all ordered, the output variables can be either categorical
(_params.svm_type=CvSVM::C_SVC or _params.svm_type=CvSVM::NU_SVC), or ordered
(_params.svm_type=CvSVM::EPS_SVR or _params.svm_type=CvSVM::NU_SVR), or not
required at all (_params.svm_type=CvSVM::ONE_CLASS), missing measurements are not
supported.
CvSVM::train_auto¶
train_auto(const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const
CvMat* _sample_idx, CvSVMParams params, int k_fold = 10, CvParamGrid C_grid =
get_default_grid(CvSVM::C), CvParamGrid gamma_grid = get_default_grid(CvSVM::GAMMA),
CvParamGrid p_grid = get_default_grid(CvSVM::P), CvParamGrid nu_grid =
get_default_grid(CvSVM::NU), CvParamGrid coef_grid = get_default_grid(CvSVM::COEF),
CvParamGrid degree_grid = get_default_grid(CvSVM::DEGREE))¶
The method trains the SVM model automatically by choosing the optimal parameters C,
gamma, p, nu, coef0, degree from CvSVMParams. By optimal one means that the cross-
validation estimate of the test set error is minimal. The parameters are iterated by a
logarithmic grid, for example, the parameter gamma takes the values in the set ( ,
, , ... ) where is gamma_grid.min_val,
is gamma_grid.step, and is the maximal index such, that
If there is no need in optimization in some parameter, the according grid step should be set
to any value less or equal to 1. For example, to avoid optimization in gamma one should set
gamma_grid.step = 0, gamma_grid.min_val, gamma_grid.max_val being arbitrary
numbers. In this case, the value params.gamma will be taken for gamma.
And, finally, if the optimization in some parameter is required, but there is no idea of the
corresponding grid, one may call the function CvSVM::get_default_grid. In order to
generate a grid, say, for gamma, call CvSVM::get_default_grid(CvSVM::GAMMA).
CvSVM::get_default_grid¶
CvParamGrid CvSVM::get_default_grid(int param_id)¶
param_id –
• CvSVM::C -
Parameter: • CvSVM::GAMMA -
• CvSVM::P -
• CvSVM::NU -
• CvSVM::COEF -
• CvSVM::DEGREE -
The grid will be generated for the parameter with this ID.
The function generates a grid for the specified parameter of the SVM algorithm. The grid may be
passed to the function CvSVM::train_auto.
CvSVM::get_params¶
CvSVMParams CvSVM::get_params() const¶
This function may be used to get the optimal parameters that were obtained while
automatically training CvSVM::train_auto.
CvSVM::get_support_vector*¶
int CvSVM::get_support_vector_count() const¶
const float* CvSVM::get_support_vector(int i) const¶
Decision Trees¶
The ML classes discussed in this section implement Classification And Regression Tree algorithms,
which are described in bgroup({#paper_Breiman84})bgroup({[Breiman84]}).
The class CvDTree represents a single decision tree that may be used alone, or as a base class in tree
ensembles (see Boosting and Random Trees).
A decision tree is a binary tree (i.e. tree where each non-leaf node has exactly 2 child nodes). It can
be used either for classification, when each tree leaf is marked with some class label (multiple leafs
may have the same label), or for regression, when each tree leaf is also assigned a constant (so the
approximation function is piecewise constant).
Sometimes, certain features of the input vector are missed (for example, in the darkness it is
difficult to determine the object color), and the prediction procedure may get stuck in the certain
node (in the mentioned example if the node is split by color). To avoid such situations, decision
trees use so-called surrogate splits. That is, in addition to the best “primary” split, every tree node
may also be split on one or more other variables with nearly the same results.
• bgroup({depth of the tree branch being constructed has reached the specified
maximum value.})
• bgroup({number of training samples in the node is less than the specified threshold,
when it is not statistically representative to split the node further.})
• bgroup({all the samples in the node belong to the same class (or, in the case of
regression, the variation is too small).})
• bgroup({the best split found does not give any noticeable improvement compared to
a random choice.})
When the tree is built, it may be pruned using a cross-validation procedure, if necessary. That is,
some branches of the tree that may lead to the model overfitting are cut off. Normally this
procedure is only applied to standalone decision trees, while tree ensembles usually build small
enough trees and use their own protection schemes against overfitting.
Variable importance¶
Besides the obvious use of decision trees - prediction, the tree can be also used for various data
analysis. One of the key properties of the constructed decision tree algorithms is that it is possible to
compute importance (relative decisive power) of each variable. For example, in a spam filter that
uses a set of words occurred in the message as a feature vector, the variable importance rating can
be used to determine the most “spam-indicating” words and thus help to keep the dictionary size
reasonable.
Importance of each variable is computed over all the splits on this variable in the tree, primary and
surrogate ones. Thus, to compute variable importance correctly, the surrogate splits must be enabled
in the training parameters, even if there is no missing data.
[Breiman84] Breiman, L., Friedman, J. Olshen, R. and Stone, C. (1984), “Classification and
Regression Trees”, Wadsworth.
CvDTreeSplit¶
Decision tree node split.
struct CvDTreeSplit
{
int var_idx;
int inversed;
float quality;
CvDTreeSplit* next;
union
{
int subset[2];
struct
{
float c;
int split_point;
}
ord;
};
};
CvDTreeNode¶
Decision tree node.
struct CvDTreeNode
{
int class_idx;
int Tn;
double value;
CvDTreeNode* parent;
CvDTreeNode* left;
CvDTreeNode* right;
CvDTreeSplit* split;
int sample_count;
int depth;
...
};
Other numerous fields of CvDTreeNode are used internally at the training stage.
CvDTreeParams¶
Decision tree training parameters.
struct CvDTreeParams
{
int max_categories;
int max_depth;
int min_sample_count;
int cv_folds;
bool use_surrogates;
bool use_1se_rule;
bool truncate_pruned_tree;
float regression_accuracy;
const float* priors;
The structure contains all the decision tree training parameters. There is a default constructor that
initializes all the parameters with the default values tuned for standalone classification tree. Any of
the parameters can be overridden then, or the structure may be fully initialized using the advanced
variant of the constructor.
CvDTreeTrainData¶
Decision tree training data and shared data for tree ensembles.
struct CvDTreeTrainData
{
CvDTreeTrainData();
CvDTreeTrainData( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
const CvDTreeParams& _params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false );
virtual ~CvDTreeTrainData();
////////////////////////////////////
CvMat* cat_count;
CvMat* cat_ofs;
CvMat* cat_map;
CvMat* counts;
CvMat* buf;
CvMat* direction;
CvMat* split_buf;
CvMat* var_idx;
CvMat* var_type; // i-th element =
// k<0 - ordered
// k>=0 - categorical, see k-th element of cat_* arrays
CvMat* priors;
CvDTreeParams params;
CvMemStorage* tree_storage;
CvMemStorage* temp_storage;
CvDTreeNode* data_root;
CvSet* node_heap;
CvSet* split_heap;
CvSet* cv_heap;
CvSet* nv_heap;
CvRNG rng;
};
This structure is mostly used internally for storing both standalone trees and tree ensembles
efficiently. Basically, it contains 3 types of information:
There are 2 ways of using this structure. In simple cases (e.g. a standalone tree, or the ready-to-use
“black box” tree ensemble from ML, like Random Trees or Boosting) there is no need to care or
even to know about the structure - just construct the needed statistical model, train it and use it. The
CvDTreeTrainData structure will be constructed and used internally. However, for custom tree
algorithms, or another sophisticated cases, the structure may be constructed and used explicitly. The
scheme is the following:
• The structure is initialized using the default constructor, followed by set_data (or it is built
using the full form of constructor). The parameter _shared must be set to true.
• One or more trees are trained using this data, see the special form of the method
CvDTree::train.
• Finally, the structure can be released only after all the trees using it are released.
CvDTree¶
Decision tree.
// special read & write methods for trees in the tree ensembles
virtual void read( CvFileStorage* fs, CvFileNode* node,
CvDTreeTrainData* data );
virtual void write( CvFileStorage* fs );
protected:
CvDTreeNode* root;
int pruned_tree_idx;
CvMat* var_importance;
CvDTreeTrainData* data;
};
CvDTree::train¶
bool CvDTree::train(const CvMat* _train_data, int _tflag, const CvMat* _responses, const
CvMat* _var_idx=0, const CvMat* _sample_idx=0, const CvMat* _var_type=0, const CvMat*
_missing_mask=0, CvDTreeParams params=CvDTreeParams())¶
bool CvDTree::train(CvDTreeTrainData* _train_data, const CvMat* _subsample_idx)
The first method follows the generic CvStatModel::train conventions, it is the most
complete form. Both data layouts (_tflag=CV_ROW_SAMPLE and _tflag=CV_COL_SAMPLE)
are supported, as well as sample and variable subsets, missing measurements, arbitrary
combinations of input and output variable types etc. The last parameter contains all of the
necessary training parameters, see the CvDTreeParams description.
The second method train is mostly used for building tree ensembles. It takes the pre-
constructed CvDTreeTrainData instance and the optional subset of training set. The indices
in _subsample_idx are counted relatively to the _sample_idx, passed to
CvDTreeTrainData constructor. For example, if _sample_idx=[1, 5, 7, 100], then
_subsample_idx=[0,3] means that the samples [1, 100] of the original training set are
used.
CvDTree::predict¶
CvDTreeNode* CvDTree::predict(const CvMat* _sample, const CvMat*
_missing_data_mask=0, bool raw_mode=false) const¶
Returns the leaf node of the decision tree corresponding to the input vector.
The method takes the feature vector and the optional missing measurement mask on input,
traverses the decision tree and returns the reached leaf node on output. The prediction result,
either the class label or the estimated function value, may be retrieved as the value field of
the CvDTreeNode structure, for example: dtree-:math:`$>$`predict(sample,mask)-
:math:`$>$`value.
The last parameter is normally set to false, implying a regular input. If it is true, the
method assumes that all the values of the discrete input variables have been already
normalized to to ranges. (as the decision tree uses such
normalized representation internally). It is useful for faster prediction with tree ensembles.
For ordered input variables the flag is not used.
Example: Building A Tree for Classifying Mushrooms. See the mushroom.cpp sample that
demonstrates how to build and use the decision tree.
Boosting¶
A common machine learning task is supervised learning. In supervised learning, the goal is to learn
the functional relationship between the input and the output . Predicting the
qualitative output is called classification, while predicting the quantitative output is called
regression.
Boosting is a powerful learning concept, which provide a solution to the supervised classification
learning task. It combines the performance of many “weak” classifiers to produce a powerful
‘committee’ HTF01. A weak classifier is only required to be better than chance, and thus can be
very simple and computationally inexpensive. Many of them smartly combined, however, results in
a strong classifier, which often outperforms most ‘monolithic’ strong classifiers such as SVMs and
Neural Networks.
Decision trees are the most popular weak classifiers used in boosting schemes. Often the simplest
decision trees with only a single split node per tree (called stumps) are sufficient.
Different variants of boosting are known such as Discrete Adaboost, Real AdaBoost, LogitBoost,
and Gentle AdaBoost FHT98. All of them are very similar in their overall structure. Therefore, we
will look only at the standard two-class Discrete AdaBoost algorithm as shown in the box below.
Each sample is initially assigned the same weight (step 2). Next a weak classifier is trained on
the weighted training data (step 3a). Its weighted training error and scaling factor is computed
(step 3b). The weights are increased for training samples, which have been misclassified (step 3c).
All weights are then normalized, and the process of finding the next weak classifier continues for
another -1 times. The final classifier is the sign of the weighted sum over the individual
weak classifiers (step 4).
Two-class Discrete AdaBoost Algorithm: Training (steps 1 to 3) and Evaluation (step 4) NOTE: As
well as the classical boosting methods, the current implementation supports 2-class classifiers only.
For M:math:$>$`2 classes there is the AdaBoost.MH algorithm, described in :ref:`FHT98, that
reduces the problem to the 2-class problem, yet with a much larger training set.
In order to reduce computation time for boosted models without substantially losing accuracy, the
influence trimming technique may be employed. As the training algorithm proceeds and the number
of trees in the ensemble is increased, a larger number of the training samples are classified correctly
and with increasing confidence, thereby those samples receive smaller weights on the subsequent
iterations. Examples with very low relative weight have small impact on training of the weak
classifier. Thus such examples may be excluded during the weak classifier training without having
much effect on the induced classifier. This process is controlled with the weight_trim_rate
parameter. Only examples with the summary fraction weight_trim_rate of the total weight mass are
used in the weak classifier training. Note that the weights for all training examples are recomputed
at each training iteration. Examples deleted at a particular iteration may be used again for learning
some of the weak classifiers further FHT98.
[HTF01] Hastie, T., Tibshirani, R., Friedman, J. H. The Elements of Statistical Learning: Data
Mining, Inference, and Prediction. Springer Series in Statistics. 2001.
[FHT98] Friedman, J. H., Hastie, T. and Tibshirani, R. Additive Logistic Regression: a Statistical
View of Boosting. Technical Report, Dept. of Statistics, Stanford University, 1998.
CvBoostParams¶
Boosting training parameters.
CvBoostParams();
CvBoostParams( int boost_type, int weak_count, double weight_trim_rate,
int max_depth, bool use_surrogates, const float* priors );
};
The structure is derived from CvDTreeParams, but not all of the decision tree parameters are
supported. In particular, cross-validation is not supported.
CvBoostTree¶
Weak tree classifier.
protected:
...
CvBoost* ensemble;
};
The weak classifier, a component of the boosted tree classifier CvBoost, is a derivative of CvDTree.
Normally, there is no need to use the weak classifiers directly, however they can be accessed as
elements of the sequence CvBoost::weak, retrieved by CvBoost::get_weak_predictors.
Note, that in the case of LogitBoost and Gentle AdaBoost each weak predictor is a regression tree,
rather than a classification tree. Even in the case of Discrete AdaBoost and Real AdaBoost the
CvBoostTree::predict return value (CvDTreeNode::value) is not the output class label; a
negative value “votes” for class 0, a positive - for class 1. And the votes are weighted. The weight
of each individual tree may be increased or decreased using the method CvBoostTree::scale.
CvBoost¶
Boosted tree classifier.
// Splitting criteria
enum { DEFAULT=0, GINI=1, MISCLASS=3, SQERR=4 };
CvBoost();
virtual ~CvBoost();
CvSeq* get_weak_predictors();
const CvBoostParams& get_params() const;
...
protected:
virtual bool set_params( const CvBoostParams& _params );
virtual void update_weights( CvBoostTree* tree );
virtual void trim_weights();
virtual void write_params( CvFileStorage* fs );
virtual void read_params( CvFileStorage* fs, CvFileNode* node );
CvDTreeTrainData* data;
CvBoostParams params;
CvSeq* weak;
...
};
CvBoost::train¶
bool CvBoost::train(const CvMat* _train_data, int _tflag, const CvMat* _responses, const
CvMat* _var_idx=0, const CvMat* _sample_idx=0, const CvMat* _var_type=0, const CvMat*
_missing_mask=0, CvBoostParams params=CvBoostParams(), bool update=false)¶
The train method follows the common template; the last parameter update specifies whether
the classifier needs to be updated (i.e. the new weak tree classifiers added to the existing
ensemble), or the classifier needs to be rebuilt from scratch. The responses must be
categorical, i.e. boosted trees can not be built for regression, and there should be 2 classes.
CvBoost::predict¶
float CvBoost::predict(const CvMat* sample, const CvMat* missing=0, CvMat*
weak_responses=0, CvSlice slice=CV_WHOLE_SEQ, bool raw_mode=false) const¶
The method CvBoost::predict runs the sample through the trees in the ensemble and
returns the output class label based on the weighted voting.
CvBoost::prune¶
void CvBoost::prune(CvSlice slice)¶
The method removes the specified weak classifiers from the sequence. Note that this method
should not be confused with the pruning of individual decision trees, which is currently not
supported.
CvBoost::get_weak_predictors¶
CvSeq* CvBoost::get_weak_predictors()¶
The method returns the sequence of weak classifiers. Each element of the sequence is a
pointer to a CvBoostTree class (or, probably, to some of its derivatives).
Random Trees¶
Random trees have been introduced by Leo Breiman and Adele Cutler:
http://www.stat.berkeley.edu/users/breiman/RandomForests/. The algorithm can deal with both
classification and regression problems. Random trees is a collection (ensemble) of tree predictors
that is called forest further in this section (the term has been also introduced by L. Breiman). The
classification works as follows: the random trees classifier takes the input feature vector, classifies
it with every tree in the forest, and outputs the class label that recieved the majority of “votes”. In
the case of regression the classifier response is the average of the responses over all the trees in the
forest.
All the trees are trained with the same parameters, but on the different training sets, which are
generated from the original training set using the bootstrap procedure: for each training set we
randomly select the same number of vectors as in the original set (=N). The vectors are chosen with
replacement. That is, some vectors will occur more than once and some will be absent. At each
node of each tree trained not all the variables are used to find the best split, rather than a random
subset of them. With each node a new subset is generated, however its size is fixed for all the nodes
and all the trees. It is a training parameter, set to by default. None of
the trees that are built are pruned.
In random trees there is no need for any accuracy estimation procedures, such as cross-validation or
bootstrap, or a separate test set to get an estimate of the training error. The error is estimated
internally during the training. When the training set for the current tree is drawn by sampling with
replacement, some vectors are left out (so-called oob (out-of-bag) data). The size of oob data is
about N/3. The classification error is estimated by using this oob-data as following:
• Get a prediction for each vector, which is oob relatively to the i-th tree, using the
very i-th tree.
• After all the trees have been trained, for each vector that has ever been oob, find the
class-“winner” for it (i.e. the class that has got the majority of votes in the trees,
where the vector was oob) and compare it to the ground-truth response.
• Then the classification error estimate is computed as ratio of number of misclassified
oob vectors to all the vectors in the original data. In the case of regression the oob-
error is computed as the squared error for oob vectors difference divided by the total
number of vectors.
References:
CvRTParams¶
Training Parameters of Random Trees.
The set of training parameters for the forest is the superset of the training parameters for a single
tree. However, Random trees do not need all the functionality/features of decision trees, most
noticeably, the trees are not pruned, so the cross-validation parameters are not used.
CvRTrees¶
Random Trees.
CvMat* get_active_var_mask();
CvRNG* get_rng();
protected:
CvRTrees::train¶
bool CvRTrees::train(const CvMat* train_data, int tflag, const CvMat* responses, const CvMat*
comp_idx=0, const CvMat* sample_idx=0, const CvMat* var_type=0, const CvMat*
missing_mask=0, CvRTParams params=CvRTParams())¶
The method CvRTrees::train is very similar to the first form of CvDTree::train`() and
follows the generic method :ctype:`CvStatModel::train conventions. All of the specific to
the algorithm training parameters are passed as a CvRTParams instance. The estimate of the
training error (oob-error) is stored in the protected class member oob_error.
CvRTrees::predict¶
double CvRTrees::predict(const CvMat* sample, const CvMat* missing=0) const¶
The input parameters of the prediction method are the same as in CvDTree::predict, but the
return value type is different. This method returns the cumulative result from all the trees in
the forest (the class that receives the majority of voices, or the mean of the regression
function estimates).
CvRTrees::get_var_importance¶
const CvMat* CvRTrees::get_var_importance() const¶
The method returns the variable importance vector, computed at the training stage when
:ref:`CvRTParams`::calc_var_importance is set. If the training flag is not set, then the NULL
pointer is returned. This is unlike decision trees, where variable importance can be
computed anytime after the training.
CvRTrees::get_proximity¶
float CvRTrees::get_proximity(const CvMat* sample_1, const CvMat* sample_2) const¶
The method returns proximity measure between any two samples (the ratio of the those trees
in the ensemble, in which the samples fall into the same leaf node, to the total number of the
trees).
#include <float.h>
#include <stdio.h>
#include <ctype.h>
#include "ml.h"
resp_col = 0;
cvGetCol( &train_data, &response, resp_col);
cvSetDefaultParamTreeClassifier((CvStatModelParams*)&cart_params);
cart_params.wrong_feature_as_unknown = 1;
params.tree_params = &cart_params;
params.term_crit.max_iter = 50;
params.term_crit.epsilon = 0.1;
params.term_crit.type = CV_TERMCRIT_ITER|CV_TERMCRIT_EPS;
cvReleaseMat(&missed);
cvReleaseMat(&sample_idx);
cvReleaseMat(&comp_idx);
cvReleaseMat(&type_mask);
cvReleaseMat(&data);
cvReleaseStatModel(&cls);
cvReleaseFileStorage(&storage);
return 0;
}
Expectation-Maximization¶
The EM (Expectation-Maximization) algorithm estimates the parameters of the multivariate
probability density function in the form of a Gaussian mixture distribution with a specified number
of mixtures.
Consider the set of the feature vectors : N vectors from a d-dimensional Euclidean
space drawn from a Gaussian mixture:
where is the number of mixtures, is the normal distribution density with the mean and
covariance matrix , is the weight of the k-th mixture. Given the number of mixtures and
the samples , the algorithm finds the maximum-likelihood estimates (MLE) of the all
the mixture parameters, i.e. , and :
EM algorithm is an iterative procedure. Each iteration of it includes two steps. At the first step
(Expectation-step, or E-step), we find a probability (denoted in the formula below) of
sample i to belong to mixture k using the currently available mixture parameter estimates:
At the second step (Maximization-step, or M-step) the mixture parameter estimates are refined
using the computed probabilities:
Alternatively, the algorithm may start with the M-step when the initial values for can be
provided. Another alternative when are unknown, is to use a simpler clustering algorithm to
pre-cluster the input samples and thus obtain initial . Often (and in ML) the KMeans2 algorithm
is used for that purpose.
One of the main that EM algorithm should deal with is the large number of parameters to estimate.
The majority of the parameters sits in covariance matrices, which are elements each (where
is the feature space dimensionality). However, in many practical problems the covariance
matrices are close to diagonal, or even to , where is identity matrix and is mixture-
dependent “scale” parameter. So a robust computation scheme could be to start with the harder
constraints on the covariance matrices and then use the estimated parameters as an input for a less
constrained optimization problem (often a diagonal covariance matrix is already a good enough
approximation).
References:
CvEMParams¶
Parameters of the EM algorithm.
struct CvEMParams
{
CvEMParams() : nclusters(10), cov_mat_type(CvEM::COV_MAT_DIAGONAL),
start_step(CvEM::START_AUTO_STEP), probs(0), weights(0), means(0),
covs(0)
{
term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
100, FLT_EPSILON );
}
int nclusters;
int cov_mat_type;
int start_step;
const CvMat* probs;
const CvMat* weights;
const CvMat* means;
const CvMat** covs;
CvTermCriteria term_crit;
};
The structure has 2 constructors, the default one represents a rough rule-of-thumb, with another one
it is possible to override a variety of parameters, from a single number of mixtures (the only
essential problem-dependent parameter), to the initial values for the mixture parameters.
CvEM¶
EM model.
CvEM();
CvEM( const CvMat* samples, const CvMat* sample_idx=0,
CvEMParams params=CvEMParams(), CvMat* labels=0 );
virtual ~CvEM();
protected:
CvMat* means;
CvMat** covs;
CvMat* weights;
CvMat* probs;
CvMat* log_weight_div_det;
CvMat* inv_eigen_values;
CvMat** cov_rotate_mats;
};
CvEM::train¶
void CvEM::train(const CvMat* samples, const CvMat* sample_idx=0, CvEMParams
params=CvEMParams(), CvMat* labels=0)¶
Unlike many of the ML models, EM is an unsupervised learning algorithm and it does not
take responses (class labels or the function values) on input. Instead, it computes the MLE of
the Gaussian mixture parameters from the input sample set, stores all the parameters inside
the structure: in probs, in means in covs[k], in weights and optionally
computes the output “class label” for each sample:
(i.e. indices of the most-probable mixture for each
sample).
The trained model can be used further for prediction, just like any other classifier. The
model trained is similar to the Bayes classifier.
#include "ml.h"
#include "highgui.h"
#if 0
// the piece of code shows how to repeatedly optimize the model
// with less-constrained parameters
//(COV_MAT_DIAGONAL instead of COV_MAT_SPHERICAL)
// when the output of the first stage is used as input for the
second.
CvEM em_model2;
params.cov_mat_type = CvEM::COV_MAT_DIAGONAL;
params.start_step = CvEM::START_E_STEP;
params.means = em_model.get_means();
params.covs = (const CvMat**)em_model.get_covs();
params.weights = em_model.get_weights();
cvReleaseMat( &samples );
cvReleaseMat( &labels );
return 0;
}
Neural Networks¶
ML implements feed-forward artificial neural networks, more particularly, multi-layer perceptrons
(MLP), the most commonly used type of neural networks. MLP consists of the input layer, output
layer and one or more hidden layers. Each layer of MLP includes one or more neurons that are
directionally linked with the neurons from the previous and the next layer. Here is an example of a
3-layer perceptron with 3 inputs, 2 outputs and the hidden layer including 5 neurons:
All the neurons in MLP are similar. Each of them has several input links (i.e. it takes the output
values from several neurons in the previous layer on input) and several output links (i.e. it passes
the response to several neurons in the next layer). The values retrieved from the previous layer are
summed with certain weights, individual for each neuron, plus the bias term, and the sum is
transformed using the activation function that may be also different for different neurons. Here is
the picture:
In other words, given the outputs of the layer , the outputs of the layer are computed
as:
Different activation functions may be used, ML implements 3 standard ones:
In ML all the neurons have the same activation functions, with the same free parameters ( ) that
are specified by user and are not altered by the training algorithms.
So the whole trained network works as follows: It takes the feature vector on input, the vector size
is equal to the size of the input layer, when the values are passed as input to the first hidden layer,
the outputs of the hidden layer are computed using the weights and the activation functions and
passed further downstream, until we compute the output layer.
So, in order to compute the network one needs to know all the weights . The weights are
computed by the training algorithm. The algorithm takes a training set: multiple input vectors with
the corresponding output vectors, and iteratively adjusts the weights to try to make the network give
the desired response on the provided input vectors.
The larger the network size (the number of hidden layers and their sizes), the more is the potential
network flexibility, and the error on the training set could be made arbitrarily small. But at the same
time the learned network will also “learn” the noise present in the training set, so the error on the
test set usually starts increasing after the network size reaches some limit. Besides, the larger
networks are train much longer than the smaller ones, so it is reasonable to preprocess the data
(using CalcPCA or similar technique) and train a smaller network on only the essential features.
Another feature of the MLP’s is their inability to handle categorical data as is, however there is a
workaround. If a certain feature in the input or output (i.e. in the case of n-class classifier for
) layer is categorical and can take different values, it makes sense to represent it as
binary tuple of M elements, where i-th element is 1 if and only if the feature is equal to the i-th
value out of M possible. It will increase the size of the input/output layer, but will speedup the
training algorithm convergence and at the same time enable “fuzzy” values of such variables, i.e. a
tuple of probabilities instead of a fixed value.
ML implements 2 algorithms for training MLP’s. The first is the classical random sequential back-
propagation algorithm and the second (default one) is batch RPROP algorithm.
References:
CvANN_MLP_TrainParams¶
Parameters of the MLP training algorithm.
struct CvANN_MLP_TrainParams
{
CvANN_MLP_TrainParams();
CvANN_MLP_TrainParams( CvTermCriteria term_crit, int train_method,
double param1, double param2=0 );
~CvANN_MLP_TrainParams();
CvTermCriteria term_crit;
int train_method;
// backpropagation parameters
double bp_dw_scale, bp_moment_scale;
// rprop parameters
double rp_dw0, rp_dw_plus, rp_dw_minus, rp_dw_min, rp_dw_max;
};
The structure has default constructor that initializes parameters for RPROP algorithm. There is also
more advanced constructor to customize the parameters and/or choose backpropagation algorithm.
Finally, the individual parameters can be adjusted after the structure is created.
CvANN_MLP¶
MLP model.
class CvANN_MLP : public CvStatModel
{
public:
CvANN_MLP();
CvANN_MLP( const CvMat* _layer_sizes,
int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual ~CvANN_MLP();
protected:
// RPROP algorithm
virtual int train_rprop( CvVectors _ivecs, CvVectors _ovecs,
const double* _sw );
CvMat* layer_sizes;
CvMat* wbuf;
CvMat* sample_weights;
double** weights;
double f_param1, f_param2;
double min_val, max_val, min_val1, max_val1;
int activ_func;
int max_count, max_buf_sz;
CvANN_MLP_TrainParams params;
CvRNG rng;
};
Unlike many other models in ML that are constructed and trained at once, in the MLP model these
steps are separated. First, a network with the specified topology is created using the non-default
constructor or the method create. All the weights are set to zeros. Then the network is trained
using the set of input and output vectors. The training procedure can be repeated more than once,
i.e. the weights can be adjusted based on the new training data.
CvANN_MLP::create¶
void CvANN_MLP::create(const CvMat* _layer_sizes, int _activ_func=SIGMOID_SYM, double
_f_param1=0, double _f_param2=0)¶
The method creates a MLP network with the specified topology and assigns the same
activation function to all the neurons.
CvANN_MLP::train¶
int CvANN_MLP::train(const CvMat* _inputs, const CvMat* _outputs, const CvMat*
_sample_weights, const CvMat* _sample_idx=0, CvANN_MLP_TrainParams _params =
CvANN_MLP_TrainParams(), int flags=0)¶
Trains/updates MLP.
This method applies the specified training algorithm to compute/adjust the network weights.
It returns the number of done iterations.
DOCUMENTO CPP
http://opencv.willowgarage.com/documentation/cpp/index.html
Introduction¶
• Namespace cv() and Function Naming
• Memory Management
• Memory Management Part II. Automatic Data Allocation
• Algebraic Operations
• Fast Element Access
• Saturation Arithmetics
• Error handling
• Threading and Reenterability
Starting from OpenCV 2.0 the new modern C++ interface has been introduced. It is crisp (less
typing is needed to code the same thing), type-safe (no more CvArr* a.k.a. void*) and, in general,
more convenient to use. Here is a short example of what it looks like:
//
// Simple retro-style photo effect done by adding noise to
// the luminance channel and reducing intensity of the chroma channels
//
// all the new API is put into "cv" namespace. Export its content
using namespace cv;
// cv::Mat replaces the CvMat and IplImage, but it's easy to convert
// between the old and the new data structures
// (by default, only the header is converted and the data is shared)
Mat img(iplimg);
#else
// the newer cvLoadImage alternative with MATLAB-style name
Mat img = imread(imagename);
#endif
Mat img_yuv;
// convert image to YUV color space.
// The output image will be allocated automatically
cvtColor(img, img_yuv, CV_BGR2YCrCb);
// blur the noise a bit, kernel size is 3x3 and both sigma's are set to 0.5
GaussianBlur(noise, noise, Size(3, 3), 0.5, 0.5);
return 0;
// all the memory will automatically be released
// by vector<>, Mat and Ptr<> destructors.
}
In the rest of the introduction we discuss the key features of the new interface in more details.
#include "cv.h"
...
cv::Mat H = cv::findHomography(points1, points2, cv::RANSAC, 5);
...
or
#include "cv.h"
...
Mat H = findHomography(points1, points2, RANSAC, 5 );
...
It is probable that some of the current or future OpenCV external names conflict with STL or other
libraries, in this case use explicit namespace specifiers to resolve the name conflicts:
For the most of the C functions and structures from OpenCV 1.x you may find the direct
counterparts in the new C++ interface. The name is usually formed by omitting cv() or Cv prefix
and turning the first letter to the low case (unless it’s a own name, like Canny, Sobel etc). In case
when there is no the new-style counterpart, it’s possible to use the old functions with the new
structures, as shown the first sample in the chapter.
Memory Management¶
When using the new interface, the most of memory deallocation and even memory allocation
operations are done automatically when needed.
First of all, Mat, SparseMat and other classes have destructors that deallocate memory buffers
occupied by the structures when needed.
Secondly, this “when needed” means that the destructors do not always deallocate the buffers, they
take into account possible data sharing. That is, in a destructor the reference counter associated with
the underlying data is decremented and the data is deallocated if and only if the reference counter
becomes zero, that is, when no other structures refer to the same buffer. When such a structure
containing a reference counter is copied, usually just the header is duplicated, while the underlying
data is not; instead, the reference counter is incremented to memorize that there is another owner of
the same data. Also, some structures, such as cvMat(), can refer to the user-allocated data. In this
case the reference counter is NULL pointer and then no reference counting is done - the data is not
deallocated by the destructors and should be deallocated manually by the user. We saw this scheme
in the first example in the chapter:
The copying semantics was mentioned in the above paragraph, but deserves a dedicated discussion.
By default, the new OpenCV structures implement shallow, so called O(1) (i.e. constant-time)
assignment operations. It gives user possibility to pass quite big data structures to functions
(though, e.g. passing const Mat is still faster than passing cvMat()), return them (e.g. see the
example with findHomography above), store them in OpenCV and STL containers etc. - and do all
of this very efficiently. On the other hand, most of the new data structures provide clone() method
that creates a full copy of an object. Here is the sample:
Memory management of the new data structures is automatic and thus easy. If, however, your code
uses IplImage, CvMat or other C data structures a lot, memory management can still be automated
without immediate migration to Mat by using the already mentioned template class Ptr, similar to
shared_ptr from Boost and C++ TR1. It wraps a pointer to an arbitrary object, provides
transparent access to all the object fields and associates a reference counter with it. Instance of the
class can be passed to any function that expects the original pointer. For correct deallocation of the
object, you should specialize Ptr<T>::delete_obj() method. Such specialized methods already
exist for the classical OpenCV structures, e.g.:
// cxoperations.hpp:
...
template<> inline Ptr<IplImage>::delete_obj() {
cvReleaseImage(&obj);
}
...
See Ptr description for more details and other usage scenarios.
Mat and other array classes provide method create that allocates a new buffer for array data if and
only if the currently allocated array is not of the required size and type. If a new buffer is needed,
the previously allocated buffer is released (by engaging all the reference counting mechanism
described in the previous section). Now, since it is very quick to check whether the needed memory
buffer is already allocated, most new OpenCV functions that have arrays as output parameters call
the create method and this way the automatic data allocation concept is implemented. Here is the
example:
#include "cv.h"
#include "highgui.h"
Mat edges;
namedWindow("edges",1);
for(;;)
{
Mat frame;
cap >> frame;
cvtColor(frame, edges, CV_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 matrix edges is allocated during the first frame processing and unless the resolution will
suddenly change, the same buffer will be reused for every next frame’s edge map.
In many cases the output array type and size can be inferenced from the input arrays’ respective
characteristics, but not always. In these rare cases the corresponding functions take separate input
parameters that specify the data type and/or size of the output arrays, like resize. Anyway, a vast
majority of the new-style array processing functions call create for each of the output array, with
just a few exceptions like mixChannels, RNG::fill and some others.
Note that this output array allocation semantic is only implemented in the new functions. If you
want to pass the new structures to some old OpenCV function, you should first allocate the output
arrays using create method, then make CvMat or IplImage headers and after that call the function.
Algebraic Operations¶
Just like in v1.x, OpenCV 2.x provides some basic functions operating on matrices, like add,
subtract, gemm etc. In addition, it introduces overloaded operators that give the user a convenient
algebraic notation, which is nearly as fast as using the functions directly. For example, here is how
the least squares problem can be solved using normal equations:
Mat x = (A.t()*A).inv()*(A.t()*b);
...
// split the image into separate color planes
vector<Mat> planes;
split(img_yuv, planes);
// method 2. process the first chroma plane using pre-stored row pointer.
// method 3. process the second chroma plane using
individual element access operations
for( int y = 0; y < img_yuv.rows; y++ )
{
uchar* Uptr = planes[1].ptr<uchar>(y);
for( int x = 0; x < img_yuv.cols; x++ )
{
Uptr[x] = saturate_cast<uchar>((Uptr[x]-128)/2 + 128);
uchar& Vxy = planes[2].at<uchar>(y, x);
Vxy = saturate_cast<uchar>((Vxy-128)/2 + 128);
}
}
merge(planes, img_yuv);
Saturation Arithmetics¶
In the above sample you may have noticed [saturatecast]bgroup({saturate_ cast}) operator, and
that’s how all the pixel processing is done in OpenCV. When a result of image operation is 8-bit
image with pixel values ranging from 0 to 255, each output pixel value is clipped to this available
range:
and the similar rules are applied to 8-bit signed and 16-bit signed and unsigned types. This
“saturation” semantics (different from usual C language “wrapping” semantics, where lowest bits
are taken, is implemented in every image processing function, from the simple cv::add() to
cv::cvtColor(), cv::resize(), cv::filter2D() etc. It is not a new feature of OpenCV v2.x, it
was there from very beginning. In the new version this special [saturatecast]bgroup({saturate_
cast}) template operator is introduced to simplify implementation of this semantic in your own
functions.
Error handling¶
The modern error handling mechanism in OpenCV uses exceptions, as opposite to the manual stack
unrolling used in previous versions. When OpenCV is built in DEBUG configuration, the error
handler provokes memory access violation, so that the full call stack and context can be analyzed
with debugger.
Basic Structures¶
DataType¶
Template “traits” class for other OpenCV primitive data types
The template class DataType is descriptive class for OpenCV primitive data types and other types
that comply with the following definition. A primitive OpenCV data type is one of unsigned
char, bool (:math:`$\sim $`unsigned char), signed char, unsigned short, signed
short, int, float, double or a tuple of values of one of these types, where all the values in the
tuple have the same type. If you are familiar with OpenCV CvMat‘s type notation, CV_8U ...
CV_32FC3, CV_64FC2 etc., then a primitive type can be defined as a type for which you can give
a unique identifier in a form CV_<bit-depth>{U|S|F}C<number_of_channels>. A universal
OpenCV structure able to store a single instance of such primitive data type is Vec. Multiple
instances of such a type can be stored to a std::vector, cvMat(), Mat_, MatND, MatND_,
SparseMat, SparseMat_ or any other container that is able to store Vec instances.
The class DataType is basically used to provide some description of such primitive data types
without adding any fields or methods to the corresponding classes (and it is actually impossible to
add anything to primitive C/C++ data types). This technique is known in C++ as class traits. It’s not
DataType itself that is used, but its specialized versions, such as:
that is, such traits are used to tell OpenCV which data type you are working with, even if such a
type is not native to OpenCV (the matrix B intialization above compiles because OpenCV defines
the proper specialized template class DataType<complex<_Tp> >). Also, this mechanism is useful
(and used in OpenCV this way) for generic algorithms implementations.
Point¶
Template class for 2D points
Point_();
Point_(_Tp _x, _Tp _y);
Point_(const Point_& pt);
Point_(const CvPoint& pt);
Point_(const CvPoint2D32f& pt);
Point_(const Size_<_Tp>& sz);
Point_(const Vec<_Tp, 2>& v);
Point_& operator = (const Point_& pt);
template<typename _Tp2> operator Point_<_Tp2>() const;
operator CvPoint() const;
operator CvPoint2D32f() const;
operator Vec<_Tp, 2>() const;
_Tp x, y;
};
The class represents a 2D point, specified by its coordinates and . Instance of the class is
interchangeable with С structures CvPoint and CvPoint2D32f. There is also cast operator to
convert point coordinates to the specified type. The conversion from floating-point coordinates to
integer coordinates is done by rounding; in general case the conversion uses
[saturatecast]bgroup({saturate_ cast}) operation on each of the coordinates. Besides the class
members listed in the declaration above, the following operations on points are implemented:
•
• pt1 = pt2 * :math:`$\alpha $`, pt1 = :math:`$\alpha $` * pt2
• pt1 += pt2, pt1 -= pt2, pt1 *= :math:`$\alpha $`
• double value = norm(pt); // :math:`$L_2$`-norm
• pt1 == pt2, pt1 != pt2
Point3¶
Template class for 3D points
Point3_();
Point3_(_Tp _x, _Tp _y, _Tp _z);
Point3_(const Point3_& pt);
explicit Point3_(const Point_<_Tp>& pt);
Point3_(const CvPoint3D32f& pt);
Point3_(const Vec<_Tp, 3>& v);
Point3_& operator = (const Point3_& pt);
template<typename _Tp2> operator Point3_<_Tp2>() const;
operator CvPoint3D32f() const;
operator Vec<_Tp, 3>() const;
_Tp x, y, z;
};
The class represents a 3D point, specified by its coordinates , and . Instance of the class is
interchangeable with С structure CvPoint2D32f. Similarly to Point_, the 3D points’ coordinates
can be converted to another type, and the vector arithmetic and comparison operations are also
supported.
Size¶
Template class for specfying image or rectangle size.
template<typename _Tp> class Size_
{
public:
typedef _Tp value_type;
Size_();
Size_(_Tp _width, _Tp _height);
Size_(const Size_& sz);
Size_(const CvSize& sz);
Size_(const CvSize2D32f& sz);
Size_(const Point_<_Tp>& pt);
Size_& operator = (const Size_& sz);
_Tp area() const;
The class Size_ is similar to Point_, except that the two members are called width and height
instead of x and y. The structure can be converted to and from the old OpenCV structures CvSize
and CvSize2D32f. The same set of arithmetic and comparison operations as for Point_ is available.
Rect¶
Template class for 2D rectangles
Rect_();
Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height);
Rect_(const Rect_& r);
Rect_(const CvRect& r);
// (x, y) <- org, (width, height) <- sz
Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz);
// (x, y) <- min(pt1, pt2), (width, height) <- max(pt1, pt2) - (x, y)
Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2);
Rect_& operator = ( const Rect_& r );
// returns Point_<_Tp>(x, y)
Point_<_Tp> tl() const;
// returns Point_<_Tp>(x+width, y+height)
Point_<_Tp> br() const;
The rectangle is described by the coordinates of the top-left corner (which is the default
interpretation of Rect_::x and Rect_::y in OpenCV; though, in your algorithms you may count x
and y from the bottom-left corner), the rectangle width and height.
Another assumption OpenCV usually makes is that the top and left boundary of the rectangle are
inclusive, while the right and bottom boundaries are not, for example, the method
Rect_::contains returns true if
And virtually every loop over an image ROI in OpenCV (where ROI is specified by Rect_<int>) is
implemented as:
In addition to the class members, the following operations on rectangles are implemented:
Example. Here is how the partial ordering on rectangles can be established (rect1 rect2):
RotatedRect¶
Possibly rotated rectangle
class RotatedRect
{
public:
// constructors
RotatedRect();
RotatedRect(const Point2f& _center, const Size2f& _size, float _angle);
RotatedRect(const CvBox2D& box);
The class RotatedRect replaces the old CvBox2D and fully compatible with it.
TermCriteria¶
Termination criteria for iterative algorithms
class TermCriteria
{
public:
enum { COUNT=1, MAX_ITER=COUNT, EPS=2 };
// constructors
TermCriteria();
// type can be MAX_ITER, EPS or MAX_ITER+EPS.
// type = MAX_ITER means that only the number of iterations does matter;
// type = EPS means that only the required precision (epsilon) does matter
// (though, most algorithms put some limit on the number of iterations
anyway)
// type = MAX_ITER + EPS means that algorithm stops when
// either the specified number of iterations is made,
// or when the specified accuracy is achieved - whatever happens first.
TermCriteria(int _type, int _maxCount, double _epsilon);
TermCriteria(const CvTermCriteria& criteria);
operator CvTermCriteria() const;
int type;
int maxCount;
double epsilon;
};
The class TermCriteria replaces the old CvTermCriteria and fully compatible with it.
Vec¶
Template class for short numerical vectors
// element access
_Tp operator [](int i) const;
_Tp& operator[](int i);
_Tp val[cn];
};
The class is the most universal representation of short numerical vectors or tuples. It is possible to
convert Vec<T,2> to/from Point_, Vec<T,3> to/from Point3_, and Vec<T,4> to CvScalar. The
elements of Vec are accessed using operator[]. All the expected vector operations are
implemented too:
The class Vec can be used for declaring various numerical objects, e.g. Vec<double,9> can be used
to store a 3x3 double-precision matrix. It is also very useful for declaring and processing multi-
channel arrays, see Mat_ description.
Scalar¶
4-element vector
The template class Scalar_ and it’s double-precision instantiation Scalar represent 4-element
vector. Being derived from Vec<_Tp, 4>, they can be used as typical 4-element vectors, but in
addition they can be converted to/from CvScalar. The type Scalar is widely used in OpenCV for
passing pixel values and it is a drop-in replacement for CvScalar that was used for the same purpose
in the earlier versions of OpenCV.
Range¶
Specifies a continuous subsequence (a.k.a. slice) of a sequence.
class Range
{
public:
Range();
Range(int _start, int _end);
Range(const CvSlice& slice);
int size() const;
bool empty() const;
static Range all();
operator CvSlice() const;
The class is used to specify a row or column span in a matrix (Mat), and for many other purposes.
Range(a,b) is basically the same as a:b in Matlab or a..b in Python. As in Python, start is
inclusive left boundary of the range, and end is exclusive right boundary of the range. Such a half-
opened interval is usually denoted as .
The static method Range::all() returns some special variable that means “the whole sequence” or
“the whole range”, just like “:” in Matlab or “...” in Python. All the methods and functions in
OpenCV that take Range support this special Range::all() value, but of course, in the case of
your own custom processing you will probably have to check and handle it explicitly:
Ptr¶
A template class for smart reference-counting pointers
The class Ptr<_Tp> is a template class that wraps pointers of the corresponding type. It is similar to
shared_ptr that is a part of Boost library
(http://www.boost.org/doc/libs/1_40_0/libs/smart_ptr/shared_ptr.htm) and also a part of the
bgroup({http://en.wikipedia.org/wiki/C
begin{itemize} item default constructor, copy constructor and assignment operator for an arbitrary
C++ class or a C structure. For some objects, like files, windows, mutexes, sockets etc, copy
constructor or assignment operator are difficult to define. For some other objects, like complex
classifiers in OpenCV, copy constructors are absent and not easy to implement. Finally, some of
complex OpenCV and your own data structures may have been written in C. However, copy
constructors and default constructors can simplify programming a lot; besides, they are often
required (e.g. by STL containers). By wrapping a pointer to such a complex object texttt{TObj} to
texttt{Ptr<TObj>} you will automatically get all of the necessary constructors and the assignment
operator.
item all the above-mentioned operations running very fast, regardless of the data size, i.e. as “O(1)”
operations. Indeed, while some structures, like texttt{std::vector} provide a copy constructor and an
assignment operator, the operations may take considerable time if the data structures are big. But if
the structures are put into texttt{Ptr<>}, the overhead becomes small and independent of the data
size.
item automatic destruction, even for C structures. See the example below with texttt{FILE*}.
item heterogeneous collections of objects. The standard STL and most other C++ and OpenCV
containers can only store objects of the same type and the same size. The classical solution to store
objects of different types in the same container is to store pointers to the base class texttt{base_
class_ t*} instead, but when you loose the automatic memory management. Again, by using
texttt{Ptr<base_ class_ t>()} instead of the raw pointers, you can solve the problem.
end{itemize}
The class texttt{Ptr} treats the wrapped object as a black box, the reference counter is allocated and
managed separately. The only thing the pointer class needs to know about the object is how to
deallocate it. This knowledge is incapsulated in texttt{Ptr::delete_ obj()} method, which is called
when the reference counter becomes 0. If the object is a C++ class instance, no additional coding is
needed, because the default implementation of this method calls texttt{delete obj;}. However, if the
object is deallocated in a different way, then the specialized method should be created. For example,
if you want to wrap texttt{FILE}, the texttt{delete_ obj} may be implemented as following:
// it is done externally.
}¶
throw ...;
fprintf(f, ....); ... // the file will be closed automatically by the Ptr<FILE> destructor. end{lstlisting}
})
Mat¶
OpenCV C++ matrix class.
class Mat
{
public:
// constructors
Mat();
// constructs matrix of the specified size and type
// (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.)
Mat(int _rows, int _cols, int _type);
// constucts matrix and fills it with the specified value _s.
Mat(int _rows, int _cols, int _type, const Scalar& _s);
Mat(Size _size, int _type);
// copy constructor
Mat(const Mat& m);
// constructor for matrix headers pointing to user-allocated data
Mat(int _rows, int _cols, int _type, void* _data, size_t _step=AUTO_STEP);
Mat(Size _size, int _type, void* _data, size_t _step=AUTO_STEP);
// creates a matrix header for a part of the bigger matrix
Mat(const Mat& m, const Range& rowRange, const Range& colRange);
Mat(const Mat& m, const Rect& roi);
// converts old-style CvMat to the new matrix; the data is not copied by
default
Mat(const CvMat* m, bool copyData=false);
// converts old-style IplImage to the new matrix; the data is not copied by
default
Mat(const IplImage* img, bool copyData=false);
// builds matrix from std::vector with or without copying the data
template<typename _Tp> Mat(const vector<_Tp>& vec, bool copyData=false);
// helper constructor to compile matrix expressions
Mat(const MatExpr_Base& expr);
// destructor - calls release()
~Mat();
// assignment operators
Mat& operator = (const Mat& m);
Mat& operator = (const MatExpr_Base& expr);
...
// returns a new matrix header for the specified row
Mat row(int y) const;
// returns a new matrix header for the specified column
Mat col(int x) const;
// ... for the specified row span
Mat rowRange(int startrow, int endrow) const;
Mat rowRange(const Range& r) const;
// ... for the specified column span
Mat colRange(int startcol, int endcol) const;
Mat colRange(const Range& r) const;
// ... for the specified diagonal
// (d=0 - the main diagonal,
// >0 - a diagonal from the lower half,
// <0 - a diagonal from the upper half)
Mat diag(int d=0) const;
// constructs a square diagonal matrix which main diagonal is vector "d"
static Mat diag(const Mat& d);
...
// sets every matrix element to s
Mat& operator = (const Scalar& s);
// sets some of the matrix elements to s, according to the mask
Mat& setTo(const Scalar& s, const Mat& mask=Mat());
// creates alternative matrix header for the same data, with different
// number of channels and/or different number of rows. see cvReshape.
Mat reshape(int _cn, int _rows=0) const;
// allocates new matrix data unless the matrix already has specified size
and type.
// previous data is unreferenced if needed.
void create(int _rows, int _cols, int _type);
void create(Size _size, int _type);
// increases the reference counter; use with care to avoid memleaks
void addref();
// decreases reference counter;
// deallocate the data when reference counter reaches 0.
void release();
The class cvMat() represents a 2D numerical array that can act as a matrix (and further it’s referred
to as a matrix), image, optical flow map etc. It is very similar to CvMat type from earlier versions of
OpenCV, and similarly to CvMat, the matrix can be multi-channel, but it also fully supports ROI
mechanism, just like IplImage.
There are many different ways to create cvMat() object. Here are the some popular ones:
As noted in the introduction of this chapter, create() will only allocate a new matrix when the
current matrix dimensionality or type are different from the specified.
• by using a copy constructor or assignment operator, where on the right side it can be a
matrix or expression, see below. Again, as noted in the introduction, matrix assignment is
O(1) operation because it only copies the header and increases the reference counter.
Mat::clone() method can be used to get a full (a.k.a. deep) copy of the matrix when you
need it.
• by constructing a header for a part of another matrix. It can be a single row, single column,
several rows, several columns, rectangular region in the matrix (called a minor in algebra) or
a diagonal. Such operations are also O(1), because the new header will reference the same
data. You can actually modify a part of the matrix using this feature, e.g.
• // add 5-th row, multiplied by 3 to the 3rd row
• M.row(3) = M.row(3) + M.row(5)*3;
•
• // now copy 7-th column to the 1-st column
• // M.col(1) = M.col(7); // this will not work
• Mat M1 = M.col(1);
• M.col(7).copyTo(M1);
•
• // create new 320x240 image
• cv::Mat img(Size(320,240),CV_8UC3);
• // select a roi
• cv::Mat roi(img, Rect(10,10,100,100));
• // fill the ROI with (0,255,0) (which is green in RGB space);
• // the original 320x240 image will be modified
• roi = Scalar(0,255,0);
Thanks to the additional datastart and dataend members, it is possible to compute the relative
sub-matrix position in the main “container” matrix using locateROI():
As in the case of whole matrices, if you need a deep copy, use clone() method of the extracted
sub-matrices.
partial yet very common cases of this “user-allocated data” case are conversions from CvMat and
IplImage to cvMat(). For this purpose there are special constructors taking pointers to CvMat or
IplImage and the optional flag indicating whether to copy the data or not.
Backward conversion from cvMat() to CvMat or IplImage is provided via cast operators
Mat::operator CvMat() const an Mat::operator IplImage(). The operators do not copy the
data.
here we first call constructor of Mat_ class (that we describe further) with the proper matrix, and
then we just put << operator followed by comma-separated values that can be constants, variables,
expressions etc. Also, note the extra parentheses that are needed to avoid compiler errors.
The next important thing to learn about the matrix class is element access. Here is how the matrix is
stored. The elements are stored in row-major order (row by row). The Mat::data member points to
the first element of the first row, Mat::rows contains the number of matrix rows and Mat::cols ‘
the number of matrix columns. There is yet another member, called Mat::step that is used to
actually compute address of a matrix element. The Mat::step is needed because the matrix can be
a part of another matrix or because there can some padding space in the end of each row for a
proper alignment.
if you know the matrix element type, e.g. it is float, then you can use at<>() method:
addr(:math:`$M_{ij}$`)=M.at<float>(i,j)
(where is used to convert the reference returned by at to a pointer). if you need to process a whole
row of matrix, the most efficient way is to get the pointer to the row first, and then just use plain C
operator []:
Some operations, like the above one, do not actually depend on the matrix shape, they just process
elements of a matrix one by one (or elements from multiple matrices that are sitting in the same
place, e.g. matrix addition). Such operations are called element-wise and it makes sense to check
whether all the input/output matrices are continuous, i.e. have no gaps in the end of each row, and if
yes, process them as a single long row:
in the case of continuous matrix the outer loop body will be executed just once, so the overhead will
be smaller, which will be especially noticeable in the case of small matrices.
Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows:
The matrix iterators are random-access iterators, so they can be passed to any STL algorithm,
including std::sort().
Matrix Expressions¶
This is a list of implemented matrix operations that can be combined in arbitrary complex
expressions (here A, B stand for matrices (cvMat()), s for a scalar (Scalar), for a real-valued
scalar (double)):
• addition, subtraction, negation:
• scaling: A*:math:`$\alpha $`, A/:math:`$\alpha $`
• per-element multiplication and division: A.mul(B), A/B, :math:`$\alpha $`/A
• matrix multiplication: A*B
• transposition: A.t() :math:`$\sim A^ t$`
• matrix inversion and pseudo-inversion, solving linear systems and least-squares problems:
A.inv([method]) :math:`$\sim A^{-1}$`, A.inv([method])*B :math:`$\sim X:\,
AX=B$`
Note, however, that comma-separated initializers and probably some other operations may require
additional explicit Mat() or Mat_<T>() constuctor calls to resolve possible ambiguity.
Mat_¶
Template matrix class derived from Mat
Mat_();
// equivalent to Mat(_rows, _cols, DataType<_Tp>::type)
Mat_(int _rows, int _cols);
// other forms of the above constructor
Mat_(int _rows, int _cols, const _Tp& value);
explicit Mat_(Size _size);
Mat_(Size _size, const _Tp& value);
// copy/conversion contructor. If m is of different type, it's converted
Mat_(const Mat& m);
// copy constructor
Mat_(const Mat_& m);
// construct a matrix on top of user-allocated data.
// step is in bytes(!!!), regardless of the type
Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP);
// minor selection
Mat_(const Mat_& m, const Range& rowRange, const Range& colRange);
Mat_(const Mat_& m, const Rect& roi);
// to support complex matrix expressions
Mat_(const MatExpr_Base& expr);
// makes a matrix out of Vec or std::vector. The matrix will have a single
column
template<int n> explicit Mat_(const Vec<_Tp, n>& vec);
Mat_(const vector<_Tp>& vec, bool copyData=false);
// iterators; they are smart enough to skip gaps in the end of rows
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
// conversion to vector.
operator vector<_Tp>() const;
};
The class Mat_<_Tp> is a “thin” template wrapper on top of cvMat() class. It does not have any
extra data fields, nor it or cvMat() have any virtual methods and thus references or pointers to these
two classes can be freely converted one to another. But do it with care, e.g.:
While cvMat() is sufficient in most cases, Mat_ can be more convenient if you use a lot of element
access operations and if you know matrix type at compile time. Note that Mat::at<_Tp>(int y,
int x) and Mat_<_Tp>::operator ()(int y, int x) do absolutely the same and run at the
same speed, but the latter is certainly shorter:
Mat_<double> M(20,20);
for(int i = 0; i < M.rows; i++)
for(int j = 0; j < M.cols; j++)
M(i,j) = 1./(i+j+1);
Mat E, V;
eigen(M,E,V);
cout << E.at<double>(0,0)/E.at<double>(M.rows-1,0);
// allocate 320x240 color image and fill it with green (in RGB space)
Mat_<Vec3b> img(240, 320, Vec3b(0,255,0));
// now draw a diagonal white line
for(int i = 0; i < 100; i++)
img(i,i)=Vec3b(255,255,255);
// and now scramble the 2nd (red) channel of each pixel
for(int i = 0; i < img.rows; i++)
for(int j = 0; j < img.cols; j++)
img(i,j)[2] ^= (uchar)(i ^ j);
MatND¶
n-dimensional dense array
class MatND
{
public:
// default constructor
MatND();
// constructs array with specific size and data type
MatND(int _ndims, const int* _sizes, int _type);
// constructs array and fills it with the specified value
MatND(int _ndims, const int* _sizes, int _type, const Scalar& _s);
// copy constructor. only the header is copied.
MatND(const MatND& m);
// sub-array selection. only the header is copied
MatND(const MatND& m, const Range* ranges);
// converts old-style nd array to MatND; optionally, copies the data
MatND(const CvMatND* m, bool copyData=false);
~MatND();
MatND& operator = (const MatND& m);
// allocates a new buffer for the data unless the current one already
// has the specified size and type.
void create(int _ndims, const int* _sizes, int _type);
// manually increment reference counter (use with care !!!)
void addref();
// decrements the reference counter. Dealloctes the data when
// the reference counter reaches zero.
void release();
// return pointer to the element (versions for 1D, 2D, 3D and generic nD
cases)
uchar* ptr(int i0);
const uchar* ptr(int i0) const;
uchar* ptr(int i0, int i1);
const uchar* ptr(int i0, int i1) const;
uchar* ptr(int i0, int i1, int i2);
const uchar* ptr(int i0, int i1, int i2) const;
uchar* ptr(const int* idx);
const uchar* ptr(const int* idx) const;
The class MatND describes n-dimensional dense numerical single-channel or multi-channel array.
This is a convenient representation for multi-dimensional histograms (when they are not very
sparse, otherwise SparseMat will do better), voxel volumes, stacked motion fields etc. The data
layout of matrix is defined by the array of M.step[], so that the address of element
, where is computed as:
which is more general form of the respective formula for Mat, wherein ,
, step[0] was simply called step, and step[1] was not stored at all but
computed as Mat::elemSize().
In other aspects MatND is also very similar to cvMat(), with the following limitations and
differences:
Here is how you can use MatND to compute NxNxN histogram of color 8bpp image (i.e. each
channel value ranges from 0..255 and we quantize it to 0..N-1):
// make sure that the histogram has proper size and type
hist.create(3, histSize, CV_32F);
// and clear it
hist = Scalar(0);
You can iterate though several matrices simultaneously as long as they have the same geometry
(dimensionality and all the dimension sizes are the same), which is useful for binary and n-ary
operations on such matrices. Just pass those matrices to MatNDIterator. Then, during the iteration
it.planes[0], it.planes[1], ... will be the slices of the corresponding matrices.
MatND_¶
Template class for n-dimensional dense array derived from MatND.
MatND_ relates to MatND almost like Mat_ to cvMat() - it provides a bit more convenient element
access operations and adds no extra members of virtual methods to the base class, thus
references/pointers to MatND_ and MatND can be easily converted one to another, e.g.
SparseMat¶
Sparse n-dimensional array.
class SparseMat
{
public:
typedef SparseMatIterator iterator;
typedef SparseMatConstIterator const_iterator;
// reallocates sparse matrix. If it was already of the proper size and type,
// it is simply cleared with clear(), otherwise,
// the old matrix is released (using release()) and the new one is
allocated.
void create(int dims, const int* _sizes, int _type);
// sets all the matrix elements to 0, which means clearing the hash table.
void clear();
// manually increases reference counter to the header.
void addref();
// decreses the header reference counter, when it reaches 0,
// the header and all the underlying data are deallocated.
void release();
// 1D case
template<typename _Tp> _Tp& ref(int i0, size_t* hashval=0);
template<typename _Tp> _Tp value(int i0, size_t* hashval=0) const;
template<typename _Tp> const _Tp* find(int i0, size_t* hashval=0) const;
// 2D case
template<typename _Tp> _Tp& ref(int i0, int i1, size_t* hashval=0);
template<typename _Tp> _Tp value(int i0, int i1, size_t* hashval=0) const;
template<typename _Tp> const _Tp* find(int i0, int i1, size_t* hashval=0)
const;
// 3D case
template<typename _Tp> _Tp& ref(int i0, int i1, int i2, size_t* hashval=0);
template<typename _Tp> _Tp value(int i0, int i1, int i2, size_t* hashval=0)
const;
template<typename _Tp> const _Tp* find(int i0, int i1, int i2, size_t*
hashval=0) const;
// n-D case
template<typename _Tp> _Tp& ref(const int* idx, size_t* hashval=0);
template<typename _Tp> _Tp value(const int* idx, size_t* hashval=0) const;
template<typename _Tp> const _Tp* find(const int* idx, size_t* hashval=0)
const;
The class SparseMat represents multi-dimensional sparse numerical arrays. Such a sparse array can
store elements of any type that Mat and MatND can store. “Sparse” means that only non-zero
elements are stored (though, as a result of operations on a sparse matrix, some of its stored elements
can actually become 0. It’s up to the user to detect such elements and delete them using
SparseMat::erase). The non-zero elements are stored in a hash table that grows when it’s filled
enough, so that the search time is O(1) in average (regardless of whether element is there or not).
Elements can be accessed using the following methods:
• query operations (SparseMat::ptr and the higher-level SparseMat::ref,
SparseMat::value and SparseMat::find), e.g.:
• const int dims = 5;
• int size[] = {10, 10, 10, 10, 10};
• SparseMat sparse_mat(dims, size, CV_32F);
• for(int i = 0; i < 1000; i++)
• {
• int idx[dims];
• for(int k = 0; k < dims; k++)
• idx[k] = rand()%sparse_mat.size(k);
• sparse_mat.ref<float>(idx) += 1.f;
• }
• sparse matrix iterators. Like Mat iterators and unlike MatND iterators, the sparse matrix
iterators are STL-style, that is, the iteration loop is familiar to C++ users:
• // prints elements of a sparse floating-point matrix
• // and the sum of elements.
• SparseMatConstIterator_<float>
• it = sparse_mat.begin<float>(),
• it_end = sparse_mat.end<float>();
• double s = 0;
• int dims = sparse_mat.dims();
• for(; it != it_end; ++it)
• {
• // print element indices and the element value
• const Node* n = it.node();
• printf("(")
• for(int i = 0; i < dims; i++)
• printf("%3d%c", n->idx[i], i < dims-1 ? ',' : ')');
• printf(": %f\n", *it);
• s += *it;
• }
• printf("Element sum is %g\n", s);
If you run this loop, you will notice that elements are enumerated in no any logical order
(lexicographical etc.), they come in the same order as they stored in the hash table, i.e. semi-
randomly. You may collect pointers to the nodes and sort them to get the proper ordering. Note,
however, that pointers to the nodes may become invalid when you add more elements to the matrix;
this is because of possible buffer reallocation.
• a combination of the above 2 methods when you need to process 2 or more sparse matrices
simultaneously, e.g. this is how you can compute unnormalized cross-correlation of the 2
floating-point sparse matrices:
• double cross_corr(const SparseMat& a, const SparseMat& b)
• {
• const SparseMat *_a = &a, *_b = &b;
• // if b contains less elements than a,
• // it's faster to iterate through b
• if(_a->nzcount() > _b->nzcount())
• std::swap(_a, _b);
• SparseMatConstIterator_<float> it = _a->begin<float>(),
• it_end = _a->end<float>();
• double ccorr = 0;
• for(; it != it_end; ++it)
• {
• // take the next element from the first matrix
• float avalue = *it;
• const Node* anode = it.node();
• // and try to find element with the same index in the second
matrix.
• // since the hash value depends only on the element index,
• // we reuse hashvalue stored in the node
• float bvalue = _b->value<float>(anode->idx,&anode->hashval);
• ccorr += avalue*bvalue;
• }
• return ccorr;
• }
SparseMat_¶
Template sparse n-dimensional array class derived from SparseMat
// constructors;
// the created matrix will have data type = DataType<_Tp>::type
SparseMat_();
SparseMat_(int dims, const int* _sizes);
SparseMat_(const SparseMat& m);
SparseMat_(const SparseMat_& m);
SparseMat_(const Mat& m);
SparseMat_(const MatND& m);
SparseMat_(const CvSparseMat* m);
// assignment operators; data type conversion is done when necessary
SparseMat_& operator = (const SparseMat& m);
SparseMat_& operator = (const SparseMat_& m);
SparseMat_& operator = (const Mat& m);
SparseMat_& operator = (const MatND& m);
// iterators
SparseMatIterator_<_Tp> begin();
SparseMatConstIterator_<_Tp> begin() const;
SparseMatIterator_<_Tp> end();
SparseMatConstIterator_<_Tp> end() const;
};
SparseMat_ is a thin wrapper on top of SparseMat, made in the same way as Mat_ and MatND_. It
simplifies notation of some operations, and that’s it.
Navigation
• index
• next |
• previous |
• OpenCV 2.0 C++ Reference »
• cxcore. The Core Functionality »
Operations on Arrays¶
abs¶
MatExpr<...> abs(const Mat& src)
The output matrix will have the same size and the same type as the input one (except for the
last case, where C will be depth=CV_8U).
absdiff¶
void absdiff(const Mat& src1, const Mat& src2, Mat& dst)
Computes per-element absolute difference between 2 arrays or between array and a scalar.
add¶
void add(const Mat& src1, const Mat& src2, Mat& dst)
void add(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask)
void add(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void add(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask)
void add(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND())
The first function in the above list can be replaced with matrix expressions:
addWeighted¶
void addWeighted(const Mat& src1, double alpha, const Mat& src2, double beta, double gamma, Mat&
dst)¶
void addWeighted(const MatND& src1, double alpha, const MatND& src2, double beta, double gamma,
MatND& dst)
cv::bitwise_and¶
Calculates per-element bit-wise conjunction of two arrays and an array and a scalar.
void bitwise_and(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat())¶
void bitwise_and(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void bitwise_and(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask=MatND())
void bitwise_and(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND())
• of two arrays
The functions bitwise_not compute per-element bit-wise inversion of the source array:
In the case of floating-point source array its machine-specific bit representation (usually
IEEE754-compliant) is used for the operation. in the case of multi-channel arrays each
channel is processed independently.
cv::bitwise_or¶
Calculates per-element bit-wise disjunction of two arrays and an array and a scalar.
void bitwise_or(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat())¶
void bitwise_or(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void bitwise_or(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask=MatND())
void bitwise_or(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND())
• of two arrays
• or array and a scalar:
cv::bitwise_xor¶
Calculates per-element bit-wise “exclusive or” operation on two arrays and an array and a scalar.
void bitwise_xor(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat())¶
void bitwise_xor(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void bitwise_xor(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask=MatND())
void bitwise_xor(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND())
The functions bitwise_xor compute per-element bit-wise logical “exclusive or” operation
• on two arrays
calcCovarMatrix¶
void calcCovarMatrix(const Mat* samples, int nsamples, Mat& covar, Mat& mean, int flags, int
ctype=CV_64F)¶
void calcCovarMatrix(const Mat& samples, Mat& covar, Mat& mean, int flags, int ctype=CV_64F)
, that is, covar will be a square matrix of the same size as the total number of elements in each
input vector. One and only one of CV_COVAR_SCRAMBLED and CV_COVAR_NORMAL must be specified
• CV_COVAR_USE_AVG - If the flag is specified, the function does not calculate mean from the input
vectors, but, instead, uses the passed mean vector. This is useful if mean has been pre-computed or
known a-priori, or if the covariance matrix is calculated by parts - in this case, mean is not a mean
vector of the input sub-set of vectors, but rather the mean vector of the whole set.
• CV_COVAR_SCALE - If the flag is specified, the covariance matrix is scaled. In the “normal” mode
scale is 1./nsamples; in the “scrambled” mode scale is the reciprocal of the total number of
elements in each input vector. By default (if the flag is not specified) the covariance matrix is not
scaled (i.e. scale=1).
• CV_COVAR_ROWS - [Only useful in the second variant of the function] The flag means that all the
input vectors are stored as rows of the samples matrix. mean should be a single-row vector in this
case.
• CV_COVAR_COLS - [Only useful in the second variant of the function] The flag means that all the
input vectors are stored as columns of the samples matrix. mean should be a single-column vector
in this case.
The functions calcCovarMatrix calculate the covariance matrix and, optionally, the mean vector
of the set of input vectors.
cartToPolar¶
void cartToPolar(const Mat& x, const Mat& y, Mat& magnitude, Mat& angle, bool
angleInDegrees=false)¶
The function cartToPolar calculates either the magnitude, angle, or both of every 2d vector
(x(I),y(I)):
The angles are calculated with accuracy. For the (0,0) point, the angle is set to 0.
checkRange¶
bool checkRange(const Mat& src, bool quiet=true, Point* pos=0, double minVal=-DBL_MAX, double
maxVal=DBL_MAX)¶
bool checkRange(const MatND& src, bool quiet=true, int* pos=0, double minVal=-DBL_MAX, double
maxVal=DBL_MAX)
The functions checkRange check that every array element is neither NaN nor . When
minVal < -DBL_MAX and maxVal < DBL_MAX, then the functions also check that each value
is between minVal and maxVal. in the case of multi-channel arrays each channel is
processed independently. If some values are out of range, position of the first outlier is
stored in pos (when ), and then the functions either return false (when
quiet=true) or throw an exception.
compare¶
void compare(const Mat& src1, const Mat& src2, Mat& dst, int cmpop)
void compare(const Mat& src1, double value, Mat& dst, int cmpop)
void compare(const MatND& src1, const MatND& src2, MatND& dst, int cmpop)
void compare(const MatND& src1, double value, MatND& dst, int cmpop)
Parameters: The flag specifying the relation between the elements to be checked
o CMP_EQ - or
o CMP_GT - or
o CMP_GE - or
o CMP_LT - or
o CMP_LE - or
o CMP_NE - or
The functions compare compare each element of src1 with the corresponding element of
src2 or with real scalar value. When the comparison result is true, the corresponding
element of destination array is set to 255, otherwise it is set to 0:
completeSymm¶
void completeSymm(Mat& mtx, bool lowerToUpper=false)¶
Copies the lower or the upper half of a square matrix to another half.
The function completeSymm copies the lower half of a square matrix to its another half; the
matrix diagonal remains unchanged:
• for if lowerToUpper=false
• for if lowerToUpper=true
convertScaleAbs¶
void convertScaleAbs(const Mat& src, Mat& dst, double alpha=1, double beta=0)¶
On each element of the input array the function convertScaleAbs performs 3 operations
sequentially: scaling, taking absolute value, conversion to unsigned 8-bit type:
in the case of multi-channel arrays the function processes each channel independently.
When the output is not 8-bit, the operation can be emulated by calling Mat::convertTo
method (or by using matrix expressions) and then by computing absolute value of the result,
for example:
Mat_<float> A(30,30);
randu(A, Scalar(-100), Scalar(100));
Mat_<float> B = A*5 + 3;
B = abs(B);
// Mat_<float> B = abs(A*5+3) will also do the job,
// but it will allocate a temporary matrix
countNonZero¶
int countNonZero(const Mat& mtx)¶
cubeRoot¶
float cubeRoot(float val)¶
The function cubeRoot computes . Negative arguments are handled correctly, NaN
and are not handled. The accuracy approaches the maximum possible accuracy for
single-precision data.
cvarrToMat¶
Mat cvarrToMat(const CvArr* src, bool copyData=false, bool allowND=true, int coiMode=0)¶
The parameter specifies how the IplImage COI (when set) is handled.
The function cvarrToMat() converts CvMat, IplImage or CvMatND header to Mat header,
and optionally duplicates the underlying data. The constructed header is returned by the
function.
When copyData=false, the conversion is done really fast (in O(1) time) and the newly
created matrix header will have refcount=0, which means that no reference counting is
done for the matrix data, and user has to preserve the data until the new header is destructed.
Otherwise, when copyData=true, the new buffer will be allocated and managed as if you
created a new matrix from scratch and copy the data there. That is, cvarrToMat(src,
true) :math:`$sim $() cvarrToMat(src, false).clone()` (assuming that COI is not set).
The function provides uniform way of supporting CvArr paradigm in the code that is
migrated to use new-style data structures internally. The reverse transformation, from Mat to
CvMat or IplImage can be done by simple assignment:
dct¶
void dct(const Mat& src, Mat& dst, int flags=0)
The function dct performs a forward or inverse discrete cosine transform (DCT) of a 1D or
2D floating-point array:
where
and , for .
The function chooses the mode of operation by looking at the flags and size of the input
array:
Important note: currently cv::dct supports even-size arrays (2, 4, 6 ...). For data analysis and
approximation you can pad the array when necessary.
Also, the function’s performance depends very much, and not monotonically, on the array
size, see getOptimalDFTSize. In the current implementation DCT of a vector of size N is
computed via DFT of a vector of size N/2, thus the optimal DCT size can be
computed as:
dft¶
void dft(const Mat& src, Mat& dst, int flags=0, int nonzeroRows=0)
• DFT_ROWS - do a forward or inverse transform of every individual row of the input matrix.
This flag allows the user to transform multiple vectors simultaneously and can be used to
decrease the overhead (which is sometimes several times larger than the processing itself),
to do 3D and higher-dimensional transforms and so forth.
• DFT_COMPLEX_OUTPUT - then the function performs forward transformation of 1D or 2D
real array, the result, though being a complex array, has complex-conjugate symmetry
(CCS), see the description below. Such an array can be packed into real array of the same
size as input, which is the fastest option and which is what the function does by default.
However, you may wish to get the full complex array (for simpler spectrum analysis etc.).
Pass the flag to tell the function to produce full-size complex output array.
• DFT_REAL_OUTPUT - then the function performs inverse transformation of 1D or 2D
complex array, the result is normally a complex array of the same size. However, if the
source array has conjugate-complex symmetry (for example, it is a result of forward
transformation with DFT_COMPLEX_OUTPUT flag), then the output is real array. While the
function itself does not check whether the input is symmetrical or not, you can pass the
flag and then the function will assume the symmetry and produce the real output array.
Note that when the input is packed real array and inverse transformation is executed, the
function treats the input as packed complex-conjugate symmetrical array, so the output
will also be real array
param nonzeroRows:
When the parameter , the function assumes that only the first nonzeroRows rows of the
input array (DFT_INVERSE is not set) or only the first nonzeroRows of the output array
(DFT_INVERSE is set) contain non-zeros, thus the function can handle the rest of the rows more
efficiently and thus save some time. This technique is very useful for computing array cross-
correlation or convolution using DFT
where and
where
Forward Fourier transform of 2D vector of elements:
In the case of real (single-channel) data, the packed format called CCS (complex-conjugate-
symmetrical) that was borrowed from IPL and used to represent the result of a forward
Fourier transform or input for an inverse Fourier transform:
in the case of 1D transform of real vector, the output will look as the first row of the above
matrix.
So, the function chooses the operation mode depending on the flags and size of the input
array:
• if DFT_ROWS is set or the input array has single row or single column then the function
performs 1D forward or inverse transform (of each row of a matrix when DFT_ROWS is set,
otherwise it will be 2D transform.
• if input array is real and DFT_INVERSE is not set, the function does forward 1D or 2D
transform:
• when DFT_COMPLEX_OUTPUT is set then the output will be complex matrix of the same
size as input.
• otherwise the output will be a real matrix of the same size as input. in the case of 2D
transform it will use the packed format as shown above; in the case of single 1D transform
it will look as the first row of the above matrix; in the case of multiple 1D transforms (when
using DCT_ROWS flag) each row of the output matrix will look like the first row of the above
matrix.
• otherwise, if the input array is complex and either DFT_INVERSE or DFT_REAL_OUTPUT
are not set then the output will be a complex array of the same size as input and the
function will perform the forward or inverse 1D or 2D transform of the whole input array or
each row of the input array independently, depending on the flags DFT_INVERSE and
DFT_ROWS.
• otherwise, i.e. when DFT_INVERSE is set, the input array is real, or it is complex but
DFT_REAL_OUTPUT is set, the output will be a real array of the same size as input, and the
function will perform 1D or 2D inverse transformation of the whole input array or each
individual row, depending on the flags DFT_INVERSE and DFT_ROWS.
Here is the sample on how to compute DFT-based convolution of two 2D real arrays:
All of the above improvements have been implemented in matchTemplate and filter2D,
therefore, by using them, you can get even better performance than with the above
theoretically optimal implementation (though, those two functions actually compute cross-
correlation, not convolution, so you will need to “flip” the kernel or the image around the
center using flip).
divide¶
void divide(const Mat& src1, const Mat& src2, Mat& dst, double scale=1)
void divide(const MatND& src1, const MatND& src2, MatND& dst, double scale=1)
The result will have the same type as src1. When src2(I)=0, dst(I)=0 too.
determinant¶
double determinant(const Mat& mtx)
Parameter: mtx – The input matrix; must have CV_32FC1 or CV_64FC1 type and square size
The function determinant computes and returns determinant of the specified matrix. For
small matrices (mtx.cols=mtx.rows<=3) the direct method is used; for larger matrices the
function uses LU factorization.
eigen¶
bool eigen(const Mat& src, Mat& eigenvalues, int lowindex=-1, int highindex=-1)
bool eigen(const Mat& src, Mat& eigenvalues, Mat& eigenvectors, int lowindex=-1, int highindex=-1)
• src – The input matrix; must have CV_32FC1 or CV_64FC1 type, square size
and be symmetric:
• eigenvalues – The output vector of eigenvalues of the same type as src; The
eigenvalues are stored in the descending order.
• eigenvectors – The output matrix of eigenvectors; It will have the same size
Parameters: and the same type as src; The eigenvectors are stored as subsequent matrix
rows, in the same order as the corresponding eigenvalues
• lowindex – Optional index of largest eigenvalue/-vector to calculate. (See
below.)
• highindex – Optional index of smallest eigenvalue/-vector to calculate. (See
below.)
If either low- or highindex is supplied the other is required, too. Indexing is 0-based.
Example: To calculate the largest eigenvector/-value set lowindex = highindex = 0. For
legacy reasons this function always returns a square matrix the same size as the source
matrix with eigenvectors and a vector the length of the source matrix with eigenvalues. The
selected eigenvectors/-values are always in the first highindex - lowindex + 1 rows.
See also: SVD, completeSymm, PCA
exp¶
void exp(const Mat& src, Mat& dst)
The function exp calculates the exponent of every element of the input array:
The maximum relative error is about for single-precision and less than for
double-precision. Currently, the function converts denormalized values to zeros on output.
Special values (NaN, ) are not handled.
extractImageCOI¶
void extractImageCOI(const CvArr* src, Mat& dst, int coi=-1)¶
The function extractImageCOI is used to extract image COI from an old-style array and
put the result to the new-style C++ matrix. As usual, the destination matrix is reallocated
using Mat::create if needed.
fastAtan2¶
float fastAtan2(float y, float x)¶
The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is
measured in degrees and varies from to . The accuracy is about .
flip¶
void flip(const Mat& src, Mat& dst, int flipCode)
The function flip flips the array in one of three different ways (row and column indices are
0-based):
gemm¶
void gemm(const Mat& src1, const Mat& src2, double alpha, const Mat& src3, double beta, Mat& dst, int
flags=0)
Performs generalized matrix multiplication.
• src1 – The first multiplied input matrix; should have CV_32FC1, CV_64FC1,
CV_32FC2 or CV_64FC2 type
• src2 – The second multiplied input matrix; should have the same type as src1
• alpha – The weight of the matrix product
• src3 – The third optional delta matrix added to the matrix product; should
have the same type as src1 and src2
• beta – The weight of src3
• dst – The destination matrix; It will have the proper size and the same type as
Parameters: input matrices
• flags –
Operation flags:
The function performs generalized matrix multiplication and similar to the corresponding
functions *gemm in BLAS level 3. For example, gemm(src1, src2, alpha, src3, beta,
dst, GEMM_1_T + GEMM_3_T) corresponds to
The function can be replaced with a matrix expression, e.g. the above call can be replaced
with:
getConvertElem¶
ConvertData getConvertElem(int fromType, int toType)¶
typedef void (*ConvertScaleData)(const void* from, void* to, int cn, double alpha, double beta)¶
getOptimalDFTSize¶
int getOptimalDFTSize(int vecsize)¶
DFT performance is not a monotonic function of a vector size, therefore, when you compute
convolution of two arrays or do a spectral analysis of array, it usually makes sense to pad the
input data with zeros to get a bit larger array that can be transformed much faster than the
original one. Arrays, which size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to
process, though, the arrays, which size is a product of 2’s, 3’s and 5’s (e.g. 300 =
5*5*3*2*2), are also processed quite efficiently.
The function getOptimalDFTSize returns the minimum number N that is greater than or
equal to vecsize, such that the DFT of a vector of size N can be computed efficiently. In the
current implementation , for some , , .
The function returns a negative number if vecsize is too large (very close to INT_MAX).
While the function cannot be used directly to estimate the optimal vector size for DCT
transform (since the current DCT implementation supports only even-size vectors), it can be
easily computed as getOptimalDFTSize((vecsize+1)/2)*2.
idct¶
void idct(const Mat& src, Mat& dst, int flags=0)
idft¶
void idft(const Mat& src, Mat& dst, int flags=0, int outputRows=0)
inRange¶
void inRange(const Mat& src, const Mat& lowerb, const Mat& upperb, Mat& dst)¶
void inRange(const Mat& src, const Scalar& lowerb, const Scalar& upperb, Mat& dst)
void inRange(const MatND& src, const MatND& lowerb, const MatND& upperb, MatND& dst)
void inRange(const MatND& src, const Scalar& lowerb, const Scalar& upperb, MatND& dst)
Checks if array elements lie between the elements of two other arrays.
The functions inRange do the range check for every element of the input array:
for single-channel arrays,
for two-channel arrays and so forth. dst``(I) is set to 255 (all ``1-bits) if ``src``(I)
is within the specified range and 0 otherwise.
invert¶
double invert(const Mat& src, Mat& dst, int method=DECOMP_LU)
The function invert inverts matrix src and stores the result in dst. When the matrix src is
singular or non-square, the function computes the pseudo-inverse matrix, i.e. the matrix dst,
such that is minimal.
In the case of DECOMP_LU method, the function returns the src determinant (src must be
square). If it is 0, the matrix is not inverted and dst is filled with zeros.
In the case of DECOMP_SVD method, the function returns the inversed condition number of
src (the ratio of the smallest singular value to the largest singular value) and 0 if src is
singular. The SVD method calculates a pseudo-inverse matrix if src is singular.
Similarly to DECOMP_LU, the method DECOMP_CHOLESKY works only with non-singular square
matrices. In this case the function stores the inverted matrix in dst and returns non-zero,
otherwise it returns 0.
log¶
void log(const Mat& src, Mat& dst)
void log(const MatND& src, MatND& dst)
The function log calculates the natural logarithm of the absolute value of every element of
the input array:
Where C is a large negative number (about -700 in the current implementation). The
maximum relative error is about for single-precision input and less than for
double-precision input. Special values (NaN, ) are not handled.
LUT¶
void LUT(const Mat& src, const Mat& lut, Mat& dst)¶
The function cvLUT() fills the destination array with values from the look-up table. Indices
of the entries are taken from the source array. That is, the function processes each element of
src as follows:
where
magnitude¶
void magnitude(const Mat& x, const Mat& y, Mat& magnitude)
The function magnitude calculates magnitude of 2D vectors formed from the corresponding
elements of x and y arrays:
Mahalanobis¶
double Mahalanobis(const Mat& vec1, const Mat& vec2, const Mat& icovar)¶
The function cvMahalonobis() calculates and returns the weighted distance between two
vectors:
The covariance matrix may be calculated using the calcCovarMatrix function and then
inverted using the invert function (preferably using DECOMP_SVD method, as the most
accurate).
max¶
Mat_Expr<...> max(const Mat& src1, const Mat& src2)
In the second variant, when the source array is multi-channel, each channel is compared
with value independently.
The first 3 variants of the function listed above are actually a part of Matrix Expressions,
they return the expression object that can be further transformed, or assigned to a matrix, or
passed to a function etc.
mean¶
Scalar mean(const Mat& mtx)
• mtx – The source array; it should have 1 to 4 channels (so that the result can
Parameters: be stored in Scalar)
• mask – The optional operation mask
The functions mean compute mean value M of array elements, independently for each
channel, and return it:
When all the mask elements are 0’s, the functions return Scalar::all(0).
meanStdDev¶
void meanStdDev(const Mat& mtx, Scalar& mean, Scalar& stddev, const Mat& mask=Mat())¶
void meanStdDev(const MatND& mtx, Scalar& mean, Scalar& stddev, const MatND& mask=MatND())
• mtx – The source array; it should have 1 to 4 channels (so that the results can
be stored in Scalar‘s)
Parameters: • mean – The output parameter: computed mean value
• stddev – The output parameter: computed standard deviation
• mask – The optional operation mask
The functions meanStdDev compute the mean and the standard deviation M of array
elements, independently for each channel, and return it via the output parameters:
When all the mask elements are 0’s, the functions return mean=stddev=Scalar::all(0).
Note that the computed standard deviation is only the diagonal of the complete normalized
covariance matrix. If the full matrix is needed, you can reshape the multi-channel array
to the single-channel array (only possible when the
matrix is continuous) and then pass the matrix to calcCovarMatrix.
merge¶
void merge(const Mat* mv, size_t count, Mat& dst)
The functions merge merge several single-channel arrays (or rather interleave their
elements) to make a single multi-channel array.
The function split does the reverse operation and if you need to merge several multi-channel
images or shuffle channels in some other advanced way, use mixChannels
min¶
Mat_Expr<...> min(const Mat& src1, const Mat& src2)
In the second variant, when the source array is multi-channel, each channel is compared
with value independently.
The first 3 variants of the function listed above are actually a part of Matrix Expressions,
they return the expression object that can be further transformed, or assigned to a matrix, or
passed to a function etc.
minMaxLoc¶
void minMaxLoc(const Mat& src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0,
const Mat& mask=Mat())¶
void minMaxLoc(const MatND& src, double* minVal, double* maxVal, int* minIdx=0, int* maxIdx=0, const
MatND& mask=MatND())
void minMaxLoc(const SparseMat& src, double* minVal, double* maxVal, int* minIdx=0, int* maxIdx=0)
The functions ninMaxLoc find minimum and maximum element values and their positions.
The extremums are searched across the whole array, or, if mask is not an empty array, in the
specified array region.
The functions do not work with multi-channel arrays. If you need to find minimum or
maximum elements across all the channels, use reshape first to reinterpret the array as
single-channel. Or you may extract the particular channel using extractImageCOI or
mixChannels or split.
in the case of a sparse matrix the minimum is found among non-zero elements only.
See also: max, min, compare, inRange, extractImageCOI, mixChannels, split, reshape.
mixChannels¶
void mixChannels(const Mat* srcv, int nsrc, Mat* dstv, int ndst, const int* fromTo, size_t npairs)¶
void mixChannels(const MatND* srcv, int nsrc, MatND* dstv, int ndst, const int* fromTo, size_t npairs)
void mixChannels(const vector<Mat>& srcv, vector<Mat>& dstv, const int* fromTo, int npairs)
void mixChannels(const vector<MatND>& srcv, vector<MatND>& dstv, const int* fromTo, int npairs)
Copies specified channels from input arrays to the specified channels of output arrays
• srcv – The input array or vector of matrices. All the matrices must have the
same size and the same depth
• nsrc – The number of elements in srcv
• dstv – The output array or vector of matrices. All the matrices must be
allocated, their size and depth must be the same as in srcv[0]
• ndst – The number of elements in dstv
• fromTo – The array of index pairs, specifying which channels are copied and
where. fromTo[k*2] is the 0-based index of the input channel in srcv and
fromTo[k*2+1] is the index of the output channel in dstv. Here the
Parameters: continuous channel numbering is used, that is, the first input image channels
are indexed from 0 to srcv[0].channels()-1, the second input image
channels are indexed from srcv[0].channels() to
srcv[0].channels() + srcv[1].channels()-1 etc., and the same
scheme is used for the output image channels. As a special case, when
fromTo[k*2] is negative, the corresponding output channel is filled with
zero. ``npairs``bgroup({The number of pairs. In the latter case the parameter
is not passed explicitly, but computed as texttt{srcv.size()}
(=texttt{dstv.size()})})
The functions mixChannels provide an advanced mechanism for shuffling image channels.
split and merge and some forms of cvtColor are partial cases of mixChannels.
As an example, this code splits a 4-channel RGBA image into a 3-channel BGR (i.e. with R
and B channels swapped) and separate alpha channel image:
Note that, unlike many other new-style C++ functions in OpenCV (see the introduction
section and Mat::create), mixChannels requires the destination arrays be pre-allocated
before calling the function.
mulSpectrums¶
void mulSpectrums(const Mat& src1, const Mat& src2, Mat& dst, int flags, bool conj=false)¶
The function, together with dft and idft, may be used to calculate convolution (pass
conj=false) or correlation (pass conj=false) of two arrays rapidly. When the arrays are
complex, they are simply multiplied (per-element) with optional conjugation of the second
array elements. When the arrays are real, they assumed to be CCS-packed (see dft for
details).
multiply¶
void multiply(const Mat& src1, const Mat& src2, Mat& dst, double scale=1)
void multiply(const MatND& src1, const MatND& src2, MatND& dst, double scale=1)
There is also Matrix Expressions-friendly variant of the first function, see Mat::mul.
If you are looking for a matrix product, not per-element product, see gemm.
See also: add, substract, divide, Matrix Expressions, scaleAdd, addWeighted, accumulate,
accumulateProduct, accumulateSquare, Mat::convertTo
mulTransposed¶
void mulTransposed(const Mat& src, Mat& dst, bool aTa, const Mat& delta=Mat(), double scale=1, int
rtype=-1)¶
The function mulTransposed calculates the product of src and its transposition:
if aTa=true, and
otherwise. The function is used to compute covariance matrix and with zero delta can be
used as a faster substitute for general matrix product when .
double norm(const Mat& src1, const Mat& src2, int normType, const Mat& mask)
double norm(const MatND& src1, const MatND& src2, int normType=NORM_L2, const MatND&
mask=MatND())
Calculates absolute array norm, absolute difference norm, or relative difference norm.
The functions norm calculate the absolute norm of src1 (when there is no src2):
or
A multiple-channel source arrays are treated as a single-channel, that is, the results for all
channels are combined.
normalize¶
void normalize(const Mat& src, Mat& dst, double alpha=1, double beta=0, int normType=NORM_L2, int
rtype=-1, const Mat& mask=Mat())
void normalize(const MatND& src, MatND& dst, double alpha=1, double beta=0, int
normType=NORM_L2, int rtype=-1, const MatND& mask=MatND())
void normalize(const SparseMat& src, SparseMat& dst, double alpha, int normType)
The functions normalize scale and shift the source array elements, so that
The optional mask specifies the sub-array to be normalize, that is, the norm or min-n-max
are computed over the sub-array and then this sub-array is modified to be normalized. If you
want to only use the mask to compute the norm or min-max, but modify the whole array,
you can use norm and
Mat::convertScale/MatND::convertScale/crossbgroup({SparseMat::convertScale})
separately.
in the case of sparse matrices, only the non-zero values are analyzed and transformed.
Because of this, the range transformation for sparse matrices is not allowed, since it can shift
the zero level.
PCA¶
Class for Principal Component Analysis
class PCA
{
public:
// default constructor
PCA();newline
// computes PCA for a set of vectors stored as data rows or columns.
PCA(const Mat& data, const Mat& mean, int flags, int
maxComponents=0);newline
// computes PCA for a set of vectors stored as data rows or columns
PCA& operator()(const Mat& data, const Mat& mean, int flags, int
maxComponents=0);newline
// projects vector into the principal components space
Mat project(const Mat& vec) const;newline
void project(const Mat& vec, Mat& result) const;newline
// reconstructs the vector from its PC projection
Mat backProject(const Mat& vec) const;newline
void backProject(const Mat& vec, Mat& result) const;newline
The class PCA is used to compute the special basis for a set of vectors. The basis will consist of
eigenvectors of the covariance matrix computed from the input set of vectors. And also the class
PCA can transform vectors to/from the new coordinate space, defined by the basis. Usually, in this
new coordinate system each vector from the original set (and any linear combination of such
vectors) can be quite accurately approximated by taking just the first few its components,
corresponding to the eigenvectors of the largest eigenvalues of the covariance matrix.
Geometrically it means that we compute projection of the vector to a subspace formed by a few
eigenvectors corresponding to the dominant eigenvalues of the covariation matrix. And usually such
a projection is very close to the original vector. That is, we can represent the original vector from a
high-dimensional space with a much shorter vector consisting of the projected vector’s coordinates
in the subspace. Such a transformation is also known as Karhunen-Loeve Transform, or KLT. See
http://en.wikipedia.org/wiki/Principal_component_analysis
The following sample is the function that takes two matrices. The first one stores the set of vectors
(a row per vector) that is used to compute PCA, the second one stores another “test” set of vectors
(a row per vector) that are first compressed with PCA, then reconstructed back and then the
reconstruction error norm is computed and printed for each vector.
PCA compressPCA(const Mat& pcaset, int maxComponents,
const Mat& testset, Mat& compressed)
{
PCA pca(pcaset, // pass the data
Mat(), // we do not have a pre-computed mean vector,
// so let the PCA engine to compute it
CV_PCA_DATA_AS_ROW, // indicate that the vectors
// are stored as matrix rows
// (use CV_PCA_DATA_AS_COL if the vectors are
// the matrix columns)
maxComponents // specify, how many principal components to retain
);
// if there is no test data, just return the computed basis, ready-to-use
if( !testset.data )
return pca;
CV_Assert( testset.cols == pcaset.cols );
Mat reconstructed;
for( int i = 0; i < testset.rows; i++ )
{
Mat vec = testset.row(i), coeffs = compressed.row(i);
// compress the vector, the result will be stored
// in the i-th row of the output matrix
pca.project(vec, coeffs);
// and then reconstruct it
pca.backProject(coeffs, reconstructed);
// and measure the error
printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2));
}
return pca;
}
perspectiveTransform¶
void perspectiveTransform(const Mat& src, Mat& dst, const Mat& mtx)¶
where
and
Note that the function transforms a sparse set of 2D or 3D vectors. If you want to transform
an image using perspective transformation, use warpPerspective. If you have an inverse
task, i.e. want to compute the most probable perspective transformation out of several pairs
of corresponding points, you can use getPerspectiveTransform or findHomography.
phase¶
void phase(const Mat& x, const Mat& y, Mat& angle, bool angleInDegrees=false)
The function phase computes the rotation angle of each 2D vector that is formed from the
corresponding elements of x and y:
See also:
polarToCart¶
void polarToCart(const Mat& magnitude, const Mat& angle, Mat& x, Mat& y, bool
angleInDegrees=false)¶
pow¶
void pow(const Mat& src, double p, Mat& dst)
That is, for a non-integer power exponent the absolute values of input array elements are
used. However, it is possible to get true values for negative values using some extra
operations, as the following example, computing the 5th root of array src, shows:
For some values of p, such as integer values, 0.5, and -0.5, specialized faster algorithms are
used.
See also: sqrt, exp, log, cartToPolar, polarToCart
randu¶
template<typename _Tp> _Tp randu()
• mtx – The output array of random numbers. The array must be pre-allocated
and have 1 to 4 channels
Parameters:
• low – The inclusive lower boundary of the generated random numbers
• high – The exclusive upper boundary of the generated random numbers
The template functions randu generate and return the next uniformly-distributed random
value of the specified type. randu<int>() is equivalent to (int)theRNG(); etc. See RNG
description.
The second non-template variant of the function fills the matrix mtx with uniformly-
distributed random numbers from the specified range:
randn¶
void randn(Mat& mtx, const Scalar& mean, const Scalar& stddev)
• mtx – The output array of random numbers. The array must be pre-allocated
and have 1 to 4 channels
Parameters:
• mean – The mean value (expectation) of the generated random numbers
• stddev – The standard deviation of the generated random numbers
The function randn fills the matrix mtx with normally distributed random numbers with the
specified mean and standard deviation. [cppfunc.saturatecast]bgroup({saturate_ cast}) is
applied to the generated numbers (i.e. the values are clipped)
randShuffle¶
void randShuffle(Mat& mtx, double iterFactor=1., RNG* rng=0)¶
Shuffles the array elements randomly
The function randShuffle shuffles the specified 1D array by randomly choosing pairs of
elements and swapping them. The number of such swap operations will be
mtx.rows*mtx.cols*iterFactor
reduce¶
void reduce(const Mat& mtx, Mat& vec, int dim, int reduceOp, int dtype=-1)
The function reduce reduces matrix to a vector by treating the matrix rows/columns as a set
of 1D vectors and performing the specified operation on the vectors until a single
row/column is obtained. For example, the function can be used to compute horizontal and
vertical projections of an raster image. In the case of CV_REDUCE_SUM and CV_REDUCE_AVG
the output may have a larger element bit-depth to preserve accuracy. And multi-channel
arrays are also supported in these two reduction modes.
See also: repeat
repeat¶
void repeat(const Mat& src, int ny, int nx, Mat& dst)
Fill the destination array with repeated copies of the source array.
The functions repeat duplicate the source array one or more times along each of the two
axes:
The second variant of the function is more convenient to use with Matrix Expressions
saturate_cast¶
Template function for accurate conversion from one primitive type to another
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 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 most simple or complex image processing functions in OpenCV.
scaleAdd¶
void scaleAdd(const Mat& src1, double scale, const Mat& src2, Mat& dst)¶
void scaleAdd(const MatND& src1, double scale, const MatND& src2, MatND& dst)
The function cvScaleAdd() is one of the classical primitive linear algebra operations,
known as DAXPY or SAXPY in
bgroup({http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms})bgroup({BLAS
}). It calculates the sum of a scaled array and another array:
The function can also be emulated with a matrix expression, for example:
The function can also be emulated using the matrix initializers and the matrix expressions:
solve¶
bool solve(const Mat& src1, const Mat& src2, Mat& dst, int flags=DECOMP_LU)
The function solve solves a linear system or least-squares problem (the latter is possible
with SVD or QR methods, or by specifying the flag DECOMP_NORMAL):
Note that if you want to find unity-norm solution of an under-defined singular system
, the function solve will not do the work. Use SVD::solveZ instead.
solveCubic¶
void solveCubic(const Mat& coeffs, Mat& roots)¶
solvePoly¶
void solvePoly(const Mat& coeffs, Mat& roots, int maxIters=20, int fig=100)¶
The function solvePoly finds real and complex roots of a polynomial equation:
sort¶
void sort(const Mat& src, Mat& dst, int flags)
The function sort sorts each matrix row or each matrix column in ascending or descending
order. If you want to sort matrix rows or columns lexicographically, you can use STL
std::sort generic function with the proper comparison predicate.
sortIdx¶
void sortIdx(const Mat& src, Mat& dst, int flags)¶
The function sortIdx sorts each matrix row or each matrix column in ascending or
descending order. Instead of reordering the elements themselves, it stores the indices of
sorted elements in the destination array. For example:
Mat A = Mat::eye(3,3,CV_32F), B;
sortIdx(A, B, CV_SORT_EVERY_ROW + CV_SORT_ASCENDING);
// B will probably contain
// (because of equal elements in A some permutations are possible):
// [[1, 2, 0], [0, 2, 1], [0, 1, 2]]
split¶
void split(const Mat& mtx, Mat* mv)
The functions split split multi-channel array into separate single-channel arrays:
sqrt¶
void sqrt(const Mat& src, Mat& dst)
void sqrt(const MatND& src, MatND& dst)
The functions sqrt calculate square root of each source array element. in the case of multi-
channel arrays each channel is processed independently. The function accuracy is
approximately the same as of the built-in std::sqrt.
subtract¶
void subtract(const Mat& src1, const Mat& src2, Mat& dst)
void subtract(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask)
void subtract(const Mat& src1, const Scalar& sc, Mat& dst, const Mat& mask=Mat())
void subtract(const Scalar& sc, const Mat& src2, Mat& dst, const Mat& mask=Mat())
void subtract(const MatND& src1, const MatND& src2, MatND& dst, const MatND& mask)
void subtract(const MatND& src1, const Scalar& sc, MatND& dst, const MatND& mask=MatND())
void subtract(const Scalar& sc, const MatND& src2, MatND& dst, const MatND& mask=MatND())
The first function in the above list can be replaced with matrix expressions:
SVD¶
Class for computing Singular Value Decomposition
class SVD
{
public:
enum { MODIFY_A=1, NO_UV=2, FULL_UV=4 };newline
// default empty constructor
SVD();newline
// decomposes m into u, w and vt: m = u*w*vt;newline
// u and vt are orthogonal, w is diagonal
SVD( const Mat& m, int flags=0 );newline
// decomposes m into u, w and vt.
SVD& operator ()( const Mat& m, int flags=0 );newline
Mat u, w, vt;
};
The class cvSVD() is used to compute Singular Value Decomposition of a floating-point matrix and
then use it to solve least-square problems, under-determined linear systems, invert matrices,
compute condition numbers etc. For a bit faster operation you can pass flags=SVD::MODIFY_A|...
to modify the decomposed matrix when it is not necessarily to preserve it. If you want to compute
condition number of a matrix or absolute value of its determinant - you do not need u and vt, so
you can pass flags=SVD::NO_UV|.... Another flag FULL_UV indicates that full-size u and vt must
be computed, which is not necessary most of the time.
The functions sum calculate and return the sum of array elements, independently for each
channel.
theRNG¶
RNG& theRNG()¶
The function theRNG returns the default random number generator. For each thread there is
separate random number generator, so you can use the function safely in multi-thread
environments. If you just need to get a single random number using this generator or
initialize an array, you can use randu or randn instead. But if you are going to generate
many random numbers inside a loop, it will be much faster to use this function to retrieve
the generator and then use RNG::operator _Tp().
trace¶
Scalar trace(const Mat& mtx)
The function trace returns the sum of the diagonal elements of the matrix mtx.
transform¶
void transform(const Mat& src, Mat& dst, const Mat& mtx)
The function transform performs matrix transformation of every element of array src and
stores the results in dst:
(when mtx.cols=src.channels()), or
(when mtx.cols=src.channels()+1)
That is, every element of an N-channel array src is considered as N-element vector, which is
transformed using a or matrix mtx into an element of M-channel array dst.
transpose¶
void transpose(const Mat& src, Mat& dst)
Transposes a matrix
If you are using your own image rendering and I/O functions, you can use any channel ordering, the
drawing functions process each channel independently and do not depend on the channel order or
even on the color space used. The whole image can be converted from BGR to RGB or to a
different color space using cvtColor.
If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also,
many drawing functions can handle pixel coordinates specified with sub-pixel accuracy, that is, the
coordinates can be passed as fixed-point numbers, encoded as integers. The number of fractional
bits is specified by the shift parameter and the real point coordinates are calculated as
. This feature is especially effective wehn
rendering antialiased shapes.
Also, note that the functions do not support alpha-transparency - when the target image is 4-
channnel, then the color[3] is simply copied to the repainted pixels. Thus, if you want to paint
semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main
image.
circle¶
void circle(Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8, int
shift=0)
Draws a circle
clipLine¶
bool clipLine(Size imgSize, Point& pt1, Point& pt2)¶
The functions clipLine calculate a part of the line segment which is entirely within the
specified rectangle. They return false if the line segment is completely outside the
rectangle and true otherwise.
ellipse¶
void ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, const
Scalar& color, int thickness=1, int lineType=8, int shift=0)
void ellipse(Mat& img, const RotatedRect& box, const Scalar& color, int thickness=1, int lineType=8)
The functions ellipse with less parameters draw an ellipse outline, a filled ellipse, an
elliptic arc or a filled ellipse sector. A piecewise-linear curve is used to approximate the
elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the
curve using ellipse2Poly and then render it with polylines or fill it with fillPoly. If you use
the first variant of the function and want to draw the whole ellipse, not an arc, pass
startAngle=0 and endAngle=360. The picture below explains the meaning of the
parameters.
ellipse2Poly¶
void ellipse2Poly(Point center, Size axes, int angle, int startAngle, int endAngle, int delta,
vector<Point>& pts)¶
The function ellipse2Poly computes the vertices of a polyline that approximates the
specified elliptic arc. It is used by ellipse.
fillConvexPoly¶
void fillConvexPoly(Mat& img, const Point* pts, int npts, const Scalar& color, int lineType=8, int
shift=0)¶
The function fillConvexPoly draws a filled convex polygon. This function is much faster
than the function fillPoly and can fill not only convex polygons but any monotonic
polygon without self-intersections, i.e., a polygon whose contour intersects every horizontal
line (scan line) twice at the most (though, its top-most and/or the bottom edge could be
horizontal).
fillPoly¶
void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int
lineType=8, int shift=0, Point offset=Point())¶
• img – Image
• pts – Array of polygons, each represented as an array of points
• npts – The array of polygon vertex counters
Parameters: • ncontours – The number of contours that bind the filled region
• color – Polygon color
• lineType – Type of the polygon boundaries, see line description
• shift – The number of fractional bits in the vertex coordinates
The function fillPoly fills an area bounded by several polygonal contours. The function
can fills complex areas, for example, areas with holes, contours with self-intersections
(some of thier parts), and so forth.
getTextSize¶
Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine)¶
int baseline=0;
Size textSize = getTextSize(text, fontFace,
fontScale, thickness, &baseline);
baseline += thickness;
line¶
void line(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
LineIterator¶
Class for iterating pixels on a raster line
class LineIterator
{
public:
// creates iterators for the line connecting pt1 and pt2
// the line will be clipped on the image boundaries
// the line is 8-connected or 4-connected
// If leftToRight=true, then the iteration is always done
// from the left-most point to the right most,
// not to depend on the ordering of pt1 and pt2 parameters
LineIterator(const Mat& img, Point pt1, Point pt2,
int connectivity=8, bool leftToRight=false);newline
// returns pointer to the current line pixel
uchar* operator *();newline
// move the iterator to the next pixel
LineIterator& operator ++();newline
LineIterator operator ++(int);newline
The class LineIterator is used to get each pixel of a raster line. It can be treated as versatile
implementation of the Bresenham algorithm, where you can stop at each pixel and do some extra
processing, for example, grab pixel values along the line, or draw a line with some effect (e.g. with
XOR operation).
rectangle¶
void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int
shift=0)
The function rectangle draws a rectangle outline or a filled rectangle, which two opposite
corners are pt1 and pt2.
polylines¶
void polylines(Mat& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const Scalar&
color, int thickness=1, int lineType=8, int shift=0)
putText¶
void putText(Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color, int
thickness=1, int lineType=8, bool bottomLeftOrigin=false)¶
o FONT_HERSHEY_PLAIN - ,
o FONT_HERSHEY_DUPLEX - ,
o FONT_HERSHEY_COMPLEX - ,
o FONT_HERSHEY_TRIPLEX - ,
o FONT_HERSHEY_COMPLEX_SMALL - ,
o FONT_HERSHEY_SCRIPT_SIMPLEX - o
• FONT_HERSHEY_SCRIPT_COMPLEX - ,
• FONT_HERSHEY_ITALIC - t
The font scale factor that is multiplied by the font-specific base size
param thickness:
param
The line type; see line for details
lineType:
param bottomLeftOrigin:
When true, the image data origin is at the bottom-left corner, otherwise it’s at the
top-left corner
The function putText draws a text string in the image. Symbols that can not be rendered
using the specified font are replaced question marks. See getTextSize for a text rendering
code example.
separately if needed.
Drawing Functions¶
Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can
be rendered with antialiasing (implemented only for 8-bit images for now). All the functions
include the parameter color that uses a rgb value (that may be constructed with CV_RGB or the
Scalar constructor) for color images and brightness for grayscale images. For color images the
order channel is normally Blue, Green, Red, this is what imshow, imread and imwrite expect , so if
you form a color using Scalar constructor, it should look like:
If you are using your own image rendering and I/O functions, you can use any channel ordering, the
drawing functions process each channel independently and do not depend on the channel order or
even on the color space used. The whole image can be converted from BGR to RGB or to a
different color space using cvtColor.
If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also,
many drawing functions can handle pixel coordinates specified with sub-pixel accuracy, that is, the
coordinates can be passed as fixed-point numbers, encoded as integers. The number of fractional
bits is specified by the shift parameter and the real point coordinates are calculated as
. This feature is especially effective wehn
rendering antialiased shapes.
Also, note that the functions do not support alpha-transparency - when the target image is 4-
channnel, then the color[3] is simply copied to the repainted pixels. Thus, if you want to paint
semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main
image.
circle¶
void circle(Mat& img, Point center, int radius, const Scalar& color, int thickness=1, int lineType=8, int
shift=0)
Draws a circle
The function circle draws a simple or filled circle with a given center and radius.
clipLine¶
bool clipLine(Size imgSize, Point& pt1, Point& pt2)¶
Parameters: • imgSize – The image size; the image rectangle will be Rect(0, 0,
imgSize.width, imgSize.height)
• imgSize – The image rectangle
• pt1 – The first line point
• pt2 – The second line point
The functions clipLine calculate a part of the line segment which is entirely within the
specified rectangle. They return false if the line segment is completely outside the
rectangle and true otherwise.
ellipse¶
void ellipse(Mat& img, Point center, Size axes, double angle, double startAngle, double endAngle, const
Scalar& color, int thickness=1, int lineType=8, int shift=0)
void ellipse(Mat& img, const RotatedRect& box, const Scalar& color, int thickness=1, int lineType=8)
The functions ellipse with less parameters draw an ellipse outline, a filled ellipse, an
elliptic arc or a filled ellipse sector. A piecewise-linear curve is used to approximate the
elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the
curve using ellipse2Poly and then render it with polylines or fill it with fillPoly. If you use
the first variant of the function and want to draw the whole ellipse, not an arc, pass
startAngle=0 and endAngle=360. The picture below explains the meaning of the
parameters.
The function ellipse2Poly computes the vertices of a polyline that approximates the
specified elliptic arc. It is used by ellipse.
fillConvexPoly¶
void fillConvexPoly(Mat& img, const Point* pts, int npts, const Scalar& color, int lineType=8, int
shift=0)¶
• img – Image
• pts – The polygon vertices
Parameters:
• npts – The number of polygon vertices
• color – Polygon color
• lineType – Type of the polygon boundaries, see line description
• shift – The number of fractional bits in the vertex coordinates
The function fillConvexPoly draws a filled convex polygon. This function is much faster
than the function fillPoly and can fill not only convex polygons but any monotonic
polygon without self-intersections, i.e., a polygon whose contour intersects every horizontal
line (scan line) twice at the most (though, its top-most and/or the bottom edge could be
horizontal).
fillPoly¶
void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int
lineType=8, int shift=0, Point offset=Point())¶
• img – Image
• pts – Array of polygons, each represented as an array of points
• npts – The array of polygon vertex counters
Parameters: • ncontours – The number of contours that bind the filled region
• color – Polygon color
• lineType – Type of the polygon boundaries, see line description
• shift – The number of fractional bits in the vertex coordinates
The function fillPoly fills an area bounded by several polygonal contours. The function
can fills complex areas, for example, areas with holes, contours with self-intersections
(some of thier parts), and so forth.
getTextSize¶
Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine)¶
The function getTextSize calculates and returns size of the box that contain the specified
text. That is, the following code will render some text, the tight box surrounding it and the
baseline:
int baseline=0;
Size textSize = getTextSize(text, fontFace,
fontScale, thickness, &baseline);
baseline += thickness;
line¶
void line(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int shift=0)
The function line draws the line segment between pt1 and pt2 points in the image. The
line is clipped by the image boundaries. For non-antialiased lines with integer coordinates
the 8-connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with
rounding endings. Antialiased lines are drawn using Gaussian filtering. To specify the line
color, the user may use the macro CV_RGB(r, g, b).
LineIterator¶
Class for iterating pixels on a raster line
class LineIterator
{
public:
// creates iterators for the line connecting pt1 and pt2
// the line will be clipped on the image boundaries
// the line is 8-connected or 4-connected
// If leftToRight=true, then the iteration is always done
// from the left-most point to the right most,
// not to depend on the ordering of pt1 and pt2 parameters
LineIterator(const Mat& img, Point pt1, Point pt2,
int connectivity=8, bool leftToRight=false);newline
// returns pointer to the current line pixel
uchar* operator *();newline
// move the iterator to the next pixel
LineIterator& operator ++();newline
LineIterator operator ++(int);newline
The class LineIterator is used to get each pixel of a raster line. It can be treated as versatile
implementation of the Bresenham algorithm, where you can stop at each pixel and do some extra
processing, for example, grab pixel values along the line, or draw a line with some effect (e.g. with
XOR operation).
rectangle¶
void rectangle(Mat& img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int lineType=8, int
shift=0)
• img – Image
• pt1 – One of the rectangle’s vertices
Parameters:
• pt2 – Opposite to pt1 rectangle vertex
• color – Rectangle color or brightness (grayscale image)
• thickness – Thickness of lines that make up the rectangle. Negative values, e.g.
CV_FILLED, mean that the function has to draw a filled rectangle.
• lineType – Type of the line, see line description
• shift – Number of fractional bits in the point coordinates
The function rectangle draws a rectangle outline or a filled rectangle, which two opposite
corners are pt1 and pt2.
polylines¶
void polylines(Mat& img, const Point** pts, const int* npts, int ncontours, bool isClosed, const Scalar&
color, int thickness=1, int lineType=8, int shift=0)
putText¶
void putText(Mat& img, const string& text, Point org, int fontFace, double fontScale, Scalar color, int
thickness=1, int lineType=8, bool bottomLeftOrigin=false)¶
o FONT_HERSHEY_PLAIN - ,
o FONT_HERSHEY_DUPLEX - ,
o FONT_HERSHEY_COMPLEX - ,
o FONT_HERSHEY_TRIPLEX - ,
o FONT_HERSHEY_COMPLEX_SMALL - ,
o FONT_HERSHEY_SCRIPT_SIMPLEX - o
• FONT_HERSHEY_SCRIPT_COMPLEX - ,
• FONT_HERSHEY_ITALIC - t
The font scale factor that is multiplied by the font-specific base size
param thickness:
param
The line type; see line for details
lineType:
param bottomLeftOrigin:
When true, the image data origin is at the bottom-left corner, otherwise it’s at the
top-left corner
The function putText draws a text string in the image. Symbols that can not be rendered
using the specified font are replaced question marks. See getTextSize for a text rendering
code example.
FileStorage¶
The XML/YAML file storage class
class FileStorage
{
public:
enum { READ=0, WRITE=1, APPEND=2 };
enum { UNDEFINED=0, VALUE_EXPECTED=1, NAME_EXPECTED=2, INSIDE_MAP=4 };
// the default constructor
FileStorage();
// the constructor that opens the file for reading
// (flags=FileStorage::READ) or writing (flags=FileStorage::WRITE)
FileStorage(const string& filename, int flags);
// wraps the already opened CvFileStorage*
FileStorage(CvFileStorage* fs);
// the destructor; closes the file if needed
virtual ~FileStorage();
// opens the specified file for reading (flags=FileStorage::READ)
// or writing (flags=FileStorage::WRITE)
virtual bool open(const string& filename, int flags);
// checks if the storage is opened
virtual bool isOpened() const;
// closes the file
virtual void release();
Ptr<CvFileStorage> fs;
string elname;
vector<char> structs;
int state;
};
FileNode¶
The XML/YAML file node class
void readRaw( const string& fmt, uchar* vec, size_t len ) const;
void* readObj() const;
FileNodeIterator¶
The XML/YAML file node iterator class
kmeans¶
double kmeans(const Mat& samples, int clusterCount, Mat& labels, TermCriteria termcrit, int attempts, int
flags, Mat* centers)
Parameters: • samples – Floating-point matrix of input samples, one row per sample
• clusterCount – The number of clusters to split the set by
• labels – The input/output integer array that will store the cluster indices for
every sample
• termcrit – Specifies maximum number of iterations and/or accuracy (distance
the centers can move by between subsequent iterations)
• attempts – How many times the algorithm is executed using different initial
labelings. The algorithm returns the labels that yield the best compactness
(see the last function parameter)
• flags –
The function kmeans implements a k-means algorithm that finds the centers of
clusterCount clusters and groups the input samples around the clusters. On output,
contains a 0-based cluster index for the sample stored in the row of the
samples matrix.
after every attempt; the best (minimum) value is chosen and the corresponding labels and
the compactness value are returned by the function. Basically, the user can use only the core
of the function, set the number of attempts to 1, initialize labels each time using some
custom algorithm and pass them with
partition¶
template<typename _Tp, class _EqPredicate> int partition(const vector<_Tp>& vec, vector<int>& labels,
_EqPredicate predicate=_EqPredicate())
flann::Index¶
The FLANN nearest neighbor index class.
namespace flann
{
class Index
{
public:
Index(const Mat& features, const IndexParams& params);
flann::Index::Index¶
Index::Index(const Mat& features, const IndexParams& params)¶
Structure containing the index parameters. The type of index that will be
constructed depends on the type of this parameter. The possible
parameter types are:
flann::Index::knnSearch¶
void Index::knnSearch(const vector<float>& query, vector<int>& indices, vector<float>& dists, int knn,
const SearchParams& params)¶
Performs a K-nearest neighbor search for a given query point using the index.
Search parameters
Parameters:
struct SearchParams {
SearchParams(int checks = 32);
};
• checks – The number of times the tree(s) in the index should be recursively
traversed. A higher value for this parameter would give better search
precision, but also take more time. If automatic configuration was used when
the index was created, the number of checks required to achieve the specified
precision was also computed, in which case this parameter is ignored.
flann::Index::knnSearch¶
void Index::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const SearchParams&
params)
flann::Index::radiusSearch¶
int Index::radiusSearch(const vector<float>& query, vector<int>& indices, vector<float>& dists, float
radius, const SearchParams& params)¶
flann::Index::radiusSearch¶
int Index::radiusSearch(const Mat& query, Mat& indices, Mat& dists, float radius, const
SearchParams& params)
flann::Index::save¶
void Index::save(std::string filename)¶
Clusters the given points by constructing a hierarchical k-means tree and choosing a cut in
the tree that minimizes the cluster’s variance.
The function returns the aligned pointer of the same type as the input pointer:
alignSize¶
size_t alignSize(size_t sz, int n)¶
Parameters:
• sz – The buffer size to align
• n – The alignment size; must be a power of two
The function returns the minimum number that is greater or equal to sz and is divisble by n:
allocate¶
template<typename _Tp> _Tp* allocate(size_t n)
The generic function allocate allocates buffer for the specified number of elements. For
each element the default constructor is called.
deallocate¶
template<typename _Tp> void deallocate(_Tp* ptr, size_t n)
The generic function deallocate deallocates the buffer allocated with allocate. The number
of elements must match the number passed to allocate.
CV_Assert¶
Checks a condition at runtime.
The macros CV_Assert and CV_DbgAssert evaluate the specified expression and if it is 0, the
macros raise an error (see 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¶
void error(const Exception& exc)
# define CV_Error( code, msg ) <...> # define CV_Error_( code, args ) <...>
The function and the helper macros CV_Error and CV_Error_ call the error handler.
Currently, the error handler prints the error code (exc.code), the context (exc.file,
exc.line and the error message exc.err to the standard error stream stderr. In Debug
configuration it then provokes memory access violation, so that the execution stack and all
the parameters can be analyzed in debugger. In Release configuration the exception exc is
thrown.
The macro CV_Error_ can be used to construct the error message on-fly to include some
dynamic information, for example:
Exception¶
The exception class passed to 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);newline
Exception(const Exception& exc);newline
Exception& operator = (const Exception& exc);newline
fastMalloc¶
void* fastMalloc(size_t size)¶
The function allocates buffer of the specified size and returns it. When the buffer size is 16
bytes or more, the returned buffer is aligned on 16 bytes.
fastFree¶
void fastFree(void* ptr)¶
The function deallocates the buffer, allocated with fastMalloc. If NULL pointer is passed,
the function does nothing.
format¶
string format(const char* fmt, ...)
The function acts like sprintf, but forms and returns STL string. It can be used for form
the error message in Exception constructor.
getNumThreads¶
int getNumThreads()¶
getThreadNum¶
int getThreadNum()¶
The function returns 0-based index of the currently executed thread. The function is only
valid inside a parallel OpenMP region. When OpenCV is built without OpenMP support, the
function always returns 0.
getTickCount¶
int64 getTickCount()¶
The function returns the number of ticks since the certain event (e.g. when the machine was
turned on). It can be used to initialize 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¶
double getTickFrequency()¶
The function returns the number of ticks per second. That is, the following code computes
the executing time in seconds.
double t = (double)getTickCount();
// do something ...
t = ((double)getTickCount() - t)/getTickFrequency();
setNumThreads¶
void setNumThreads(int nthreads)¶
Image Filtering¶
Functions and classes described in this section are used to perform various linear or non-linear
filtering operations on 2D images (represented as Mat‘s), that is, for each pixel location in the
source image some its (normally rectangular) neighborhood is considered and used to compute the
response. In case of a linear filter it is a weighted sum of pixel values, in case of morphological
operations it is the minimum or maximum etc. The computed response is stored to the destination
image at the same location . It means, that the output image will be of the same size as the
input image. Normally, the functions supports multi-channel arrays, in which case every channel is
processed independently, therefore the output image will also have the same number of channels as
the input one.
Another common feature of the functions and classes described in this section is that, unlike simple
arithmetic functions, they need to extrapolate values of some non-existing pixels. For example, if
we want to smooth an image using a Gaussian filter, then during the processing of the left-
most pixels in each row we need pixels to the left of them, i.e. outside of the image. We can let
those pixels be the same as the left-most image pixels (i.e. use “replicated border” extrapolation
method), or assume that all the non-existing pixels are zeros (“contant border” extrapolation
method) etc. OpenCV let the user to specify the extrapolation method; see the function
borderInterpolate and discussion of borderType parameter in various functions below.
BaseColumnFilter¶
Base class for filters with single-column kernels
class BaseColumnFilter
{
public:
virtual ~BaseColumnFilter();
where is the filtering function, but, as it is represented as a class, it can produce any side effects,
memorize previously processed data etc. The class only defines the interface and is not used
directly. Instead, there are several functions in OpenCV (and you can add more) that return pointers
to the derived classes that implement specific filtering operations. Those pointers are then passed to
FilterEngine constructor. While the filtering operation interface uses uchar type, a particular
implementation is not limited to 8-bit data.
BaseFilter¶
Base class for 2D image filters
class BaseFilter
{
public:
virtual ~BaseFilter();
The class BaseFilter is the base class for filtering data using 2D kernels. The filtering does not
have to be a linear operation. In general, it could be written as following:
where is the filtering function. The class only defines the interface and is not used directly.
Instead, there are several functions in OpenCV (and you can add more) that return pointers to the
derived classes that implement specific filtering operations. Those pointers are then passed to
FilterEngine constructor. While the filtering operation interface uses uchar type, a particular
implementation is not limited to 8-bit data.
BaseRowFilter¶
Base class for filters with single-row kernels
class BaseRowFilter
{
public:
virtual ~BaseRowFilter();
The class BaseRowFilter is the base class for filtering data using single-row kernels. The filtering
does not have to be a linear operation. In general, it could be written as following:
where is the filtering function. The class only defines the interface and is not used directly.
Instead, there are several functions in OpenCV (and you can add more) that return pointers to the
derived classes that implement specific filtering operations. Those pointers are then passed to
FilterEngine constructor. While the filtering operation interface uses uchar type, a particular
implementation is not limited to 8-bit data.
FilterEngine¶
Generic image filtering class
class FilterEngine
{
public:
// empty constructor
FilterEngine();
// builds a 2D non-separable filter (!_filter2D.empty()) or
// a separable filter (!_rowFilter.empty() && !_columnFilter.empty())
// the input data type will be "srcType", the output data type will be
"dstType",
// the intermediate data type is "bufType".
// _rowBorderType and _columnBorderType determine how the image
// will be extrapolated beyond the image boundaries.
// _borderValue is only used when _rowBorderType and/or _columnBorderType
// == cv::BORDER_CONSTANT
FilterEngine(const Ptr<BaseFilter>& _filter2D,
const Ptr<BaseRowFilter>& _rowFilter,
const Ptr<BaseColumnFilter>& _columnFilter,
int srcType, int dstType, int bufType,
int _rowBorderType=BORDER_REPLICATE,
int _columnBorderType=-1, // use _rowBorderType by default
const Scalar& _borderValue=Scalar());
virtual ~FilterEngine();
// separate function for the engine initialization
void init(const Ptr<BaseFilter>& _filter2D,
const Ptr<BaseRowFilter>& _rowFilter,
const Ptr<BaseColumnFilter>& _columnFilter,
int srcType, int dstType, int bufType,
int _rowBorderType=BORDER_REPLICATE, int _columnBorderType=-1,
const Scalar& _borderValue=Scalar());
// starts filtering of the ROI in an image of size "wholeSize".
// returns the starting y-position in the source image.
virtual int start(Size wholeSize, Rect roi, int maxBufRows=-1);
// alternative form of start that takes the image
// itself instead of "wholeSize". Set isolated to true to pretend that
// there are no real pixels outside of the ROI
// (so that the pixels will be extrapolated using the specified border
modes)
virtual int start(const Mat& src, const Rect& srcRoi=Rect(0,0,-1,-1),
bool isolated=false, int maxBufRows=-1);
// processes the next portion of the source image,
// "srcCount" rows starting from "src" and
// stores the results to "dst".
// returns the number of produced rows
virtual int proceed(const uchar* src, int srcStep, int srcCount,
uchar* dst, int dstStep);
// higher-level function that processes the whole
// ROI or the whole image with a single call
virtual void apply( const Mat& src, Mat& dst,
const Rect& srcRoi=Rect(0,0,-1,-1),
Point dstOfs=Point(0,0),
bool isolated=false);
bool isSeparable() const { return filter2D.empty(); }
// how many rows from the input image are not yet processed
int remainingInputRows() const;
// how many output rows are not yet produced
int remainingOutputRows() const;
...
// the starting and the ending rows in the source image
int startY, endY;
The class FilterEngine can be used to apply an arbitrary filtering operation to an image. It
contains all the necessary intermediate buffers, it computes extrapolated values of the “virtual”
pixels outside of the image etc. Pointers to the initialized FilterEngine instances are returned by
various create*Filter functions, see below, and they are used inside high-level functions such as
filter2D, erode, dilate etc, that is, the class is the workhorse in many of OpenCV filtering functions.
This class makes it easier (though, maybe not very easy yet) to combine filtering operations with
other operations, such as color space conversions, thresholding, arithmetic operations, etc. By
combining several operations together you can get much better performance because your data will
stay in cache. For example, below is the implementation of Laplace operator for a floating-point
images, which is a simplified implementation of Laplacian:
If you do not need that much control of the filtering process, you can simply use the
FilterEngine::apply method. Here is how the method is actually implemented:
void FilterEngine::apply(const Mat& src, Mat& dst,
const Rect& srcRoi, Point dstOfs, bool isolated)
{
// check matrix types
CV_Assert( src.type() == srcType && dst.type() == dstType );
// start filtering
int y = start(src, _srcRoi, isolated);
// process the whole ROI. Note that "endY - startY" is the total number
// of the source rows to process
// (including the possible rows outside of srcRoi but inside the source
image)
proceed( src.data + y*src.step,
(int)src.step, endY - startY,
dst.data + dstOfs.y*dst.step +
dstOfs.x*dst.elemSize(), (int)dst.step );
}
Unlike the earlier versions of OpenCV, now the filtering operations fully support the notion of
image ROI, that is, pixels outside of the ROI but inside the image can be used in the filtering
operations. For example, you can take a ROI of a single pixel and filter it - that will be a filter
response at that particular pixel (however, it’s possible to emulate the old behavior by passing
isolated=false to FilterEngine::start or FilterEngine::apply). You can pass the ROI
explicitly to FilterEngine::apply, or construct a new matrix headers:
// method 1:
// form a matrix header for a single value
float val1 = 0;
Mat dst1(1,1,CV_32F,&val1);
// method 2:
// form a matrix header for a single value
float val2 = 0;
Mat dst2(1,1,CV_32F,&val2);
bilateralFilter¶
void bilateralFilter(const Mat& src, Mat& dst, int d, double sigmaColor, double sigmaSpace, int
borderType=BORDER_DEFAULT)¶
blur¶
void blur(const Mat& src, Mat& dst, Size ksize, Point anchor=Point(-1, -1), int
borderType=BORDER_DEFAULT)
borderInterpolate¶
int borderInterpolate(int p, int len, int borderType)¶
• p – 0-based coordinate of the extrapolated pixel along one of the axes, likely
<0 or >=``len``
• len – length of the array along the corresponding axis
Parameters: • borderType – the border type, one of the BORDER_*, except for
BORDER_TRANSPARENT and BORDER_ISOLATED. When
borderType==BORDER_CONSTANT the function always returns -1, regardless
of p and len
The function computes and returns the coordinate of the donor pixel, corresponding to the
specified extrapolated pixel when using the specified extrapolation border mode. For
example, if we use BORDER_WRAP mode in the horizontal direction, BORDER_REFLECT_101 in
the vertical direction and want to compute value of the “virtual” pixel Point(-5, 100) in a
floating-point image img, it will be
Normally, the function is not called directly; it is used inside FilterEngine and
copyMakeBorder to compute tables for quick extrapolation.
See also: FilterEngine, copyMakeBorder
boxFilter¶
void boxFilter(const Mat& src, Mat& dst, int ddepth, Size ksize, Point anchor=Point(-1, -1), bool
normalize=true, int borderType=BORDER_DEFAULT)¶
where
Unnormalized box filter is useful for computing various integral characteristics over each
pixel neighborhood, such as covariation matrices of image derivatives (used in dense optical
flow algorithms, [conerHarris]bgroup({Harris corner detector}) etc.). If you need to
compute pixel sums over variable-size windows, use integral.
buildPyramid¶
void buildPyramid(const Mat& src, vector<Mat>& dst, int maxlevel)¶
• src – The source image; check pyrDown for the list of supported types
Parameters:
• dst – The destination vector of maxlevel+1 images of the same type as src;
dst[0] will be the same as src, dst[1] is the next pyramid layer, a
smoothed and down-sized src etc.
• maxlevel – The 0-based index of the last (i.e. the smallest) pyramid layer; it
must be non-negative
The function constructs a vector of images and builds the gaussian pyramid by recursively
applying pyrDown to the previously built pyramid layers, starting from dst[0]==src.
copyMakeBorder¶
void copyMakeBorder(const Mat& src, Mat& dst, int top, int bottom, int left, int right, int borderType,
const Scalar& value=Scalar())¶
The function copies the source image into the middle of the destination image. The areas to
the left, to the right, above and below the copied source image will be filled with
extrapolated pixels. This is not what FilterEngine or based on it filtering functions do (they
extrapolate pixels on-fly), but what other more complex functions, including your own, may
do to simplify image boundary handling.
The function supports the mode when src is already in the middle of dst. In this case the
function does not copy src itself, but simply constructs the border, e.g.:
createBoxFilter¶
Ptr<FilterEngine> createBoxFilter(int srcType, int dstType, Size ksize, Point anchor=Point(-1, -1), bool
normalize=true, int borderType=BORDER_DEFAULT)¶
Ptr<BaseColumnFilter> getColumnSumFilter(int sumType, int dstType, int ksize, int anchor=-1, double
scale=1)¶
The function is a convenience function that retrieves horizontal sum primitive filter with
getRowSumFilter, vertical sum filter with getColumnSumFilter, constructs new FilterEngine
and passes both of the primitive filters there. The constructed filter engine can be used for
image filtering with normalized or unnormalized box filter.
createDerivFilter¶
Ptr<FilterEngine> createDerivFilter(int srcType, int dstType, int dx, int dy, int ksize, int
borderType=BORDER_DEFAULT)¶
createGaussianFilter¶
Ptr<FilterEngine> createGaussianFilter(int type, Size ksize, double sigmaX, double sigmaY=0, int
borderType=BORDER_DEFAULT)¶
The function createGaussianFilter computes Gaussian kernel coefficients and then returns
separable linear filter for that kernel. The function is used by GaussianBlur. Note that while
the function takes just one data type, both for input and output, you can pass by this
limitation by calling getGaussianKernel and then createSeparableFilter directly.
createLinearFilter¶
Ptr<FilterEngine> createLinearFilter(int srcType, int dstType, const Mat& kernel, Point
_anchor=Point(-1, -1), double delta=0, int rowBorderType=BORDER_DEFAULT, int columnBorderType=-1,
const Scalar& borderValue=Scalar())¶
Ptr<BaseFilter> getLinearFilter(int srcType, int dstType, const Mat& kernel, Point anchor=Point(-1, -1),
double delta=0, int bits=0)¶
The function returns pointer to 2D linear filter for the specified kernel, the source array type
and the destination array type. The function is a higher-level function that calls
getLinearFilter and passes the retrieved 2D filter to FilterEngine constructor.
createMorphologyFilter¶
Ptr<FilterEngine> createMorphologyFilter(int op, int type, const Mat& element, Point anchor=Point(-
1, -1), int rowBorderType=BORDER_CONSTANT, int columnBorderType=-1, const Scalar&
borderValue=morphologyDefaultBorderValue())¶
Ptr<BaseFilter> getMorphologyFilter(int op, int type, const Mat& element, Point anchor=Point(-1, -1))¶
The functions construct primitive morphological filtering operations or a filter engine based
on them. Normally it’s enough to use createMorphologyFilter or even higher-level erode,
dilate or morphologyEx, Note, that createMorphologyFilter analyses the structuring element
shape and builds a separable morphological filter engine when the structuring element is
square.
createSeparableLinearFilter¶
Ptr<FilterEngine> createSeparableLinearFilter(int srcType, int dstType, const Mat& rowKernel,
const Mat& columnKernel, Point anchor=Point(-1, -1), double delta=0, int
rowBorderType=BORDER_DEFAULT, int columnBorderType=-1, const Scalar& borderValue=Scalar())¶
Ptr<BaseRowFilter> getLinearRowFilter(int srcType, int bufType, const Mat& rowKernel, int anchor, int
symmetryType)¶
The functions construct primitive separable linear filtering operations or a filter engine
based on them. Normally it’s enough to use createSeparableLinearFilter or even higher-
level sepFilter2D. The function createMorphologyFilter is smart enough to figure out the
symmetryType for each of the two kernels, the intermediate bufType, and, if the filtering
can be done in integer arithmetics, the number of bits to encode the filter coefficients. If it
does not work for you, it’s possible to call getLinearColumnFilter, getLinearRowFilter
directly and then pass them to FilterEngine constructor.
dilate¶
void dilate(const Mat& src, Mat& dst, const Mat& element, Point anchor=Point(-1, -1), int iterations=1,
int borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue())
The function dilates the source image using the specified structuring element that determines
the shape of a pixel neighborhood over which the maximum is taken:
The function supports the in-place mode. Dilation can be applied several (iterations)
times. In the case of multi-channel images each channel is processed independently.
erode¶
void erode(const Mat& src, Mat& dst, const Mat& element, Point anchor=Point(-1, -1), int iterations=1, int
borderType=BORDER_CONSTANT, const Scalar& borderValue=morphologyDefaultBorderValue())
The function supports the in-place mode. Erosion can be applied several (iterations)
times. In the case of multi-channel images each channel is processed independently.
filter2D¶
void filter2D(const Mat& src, Mat& dst, int ddepth, const Mat& kernel, Point anchor=Point(-1, -1),
double delta=0, int borderType=BORDER_DEFAULT)¶
The function applies an arbitrary linear filter to the image. In-place operation is supported.
When the aperture is partially outside the image, the function interpolates outlier pixel
values according to the specified border mode.
That is, the kernel is not mirrored around the anchor point. If you need a real convolution,
flip the kernel using flip and set the new anchor to (kernel.cols - anchor.x - 1,
kernel.rows - anchor.y - 1).
The function uses [dft]bgroup({DFT})-based algorithm in case of sufficiently large kernels (
) and the direct algorithm (that uses the engine retrieved by createLinearFilter) for
small kernels.
GaussianBlur¶
void GaussianBlur(const Mat& src, Mat& dst, Size ksize, double sigmaX, double sigmaY=0, int
borderType=BORDER_DEFAULT)¶
The function convolves the source image with the specified Gaussian kernel. In-place
filtering is supported.
getDerivKernels¶
void getDerivKernels(Mat& kx, Mat& ky, int dx, int dy, int ksize, bool normalize=false, int
ktype=CV_32F)¶
• kx – The output matrix of row filter coefficients; will have type ktype
• ky – The output matrix of column filter coefficients; will have type ktype
• dx – The derivative order in respect with x
• dy – The derivative order in respect with y
Parameters: • ksize – The aperture size. It can be CV_SCHARR, 1, 3, 5 or 7
• normalize – Indicates, whether to normalize (scale down) the filter
coefficients or not. In theory the coefficients should have the denominator
. If you are going to filter floating-point images, you will
likely want to use the normalized kernels. But if you compute derivatives of a
8-bit image, store the results in 16-bit image and wish to preserve all the
fractional bits, you may want to set normalize=false.
• ktype – The type of filter coefficients. It can be CV_32f or CV_64F
The function computes and returns the filter coefficients for spatial image derivatives. When
ksize=CV_SCHARR, the Scharr kernels are generated, see Scharr. Otherwise, Sobel
kernels are generated, see Sobel. The filters are normally passed to sepFilter2D or to
createSeparableLinearFilter.
getGaussianKernel¶
Mat getGaussianKernel(int ksize, double sigma, int ktype=CV_64F)¶
The function computes and returns the matrix of Gaussian filter coefficients:
getKernelType¶
int getKernelType(const Mat& kernel, Point anchor)¶
The function analyzes the kernel coefficients and returns the corresponding kernel type:
• KERNEL_GENERAL - Generic kernel - when there is no any type of symmetry or other
properties
• KERNEL_SYMMETRICAL - The kernel is symmetrical:
and the anchor is at the center
• KERNEL_ASYMMETRICAL - The kernel is asymmetrical:
and the anchor is at the center
• KERNEL_SMOOTH - All the kernel elements are non-negative and sum to 1. E.g. the
Gaussian kernel is both smooth kernel and symmetrical, so the function will return
KERNEL_SMOOTH | KERNEL_SYMMETRICAL
• KERNEL_INTEGER - Al the kernel coefficients are integer numbers. This flag can be
combined with KERNEL_SYMMETRICAL or KERNEL_ASYMMETRICAL
getStructuringElement¶
Mat getStructuringElement(int shape, Size esize, Point anchor=Point(-1, -1))¶
Returns the structuring element of the specified size and shape for morphological operations
• shape –
The function constructs and returns the structuring element that can be then passed to
createMorphologyFilter, erode, dilate or morphologyEx. But also you can construct an
arbitrary binary mask yourself and use it as the structuring element.
medianBlur¶
void medianBlur(const Mat& src, Mat& dst, int ksize)¶
Smoothes image using median filter
• src – The source 1-, 3- or 4-channel image. When ksize is 3 or 5, the image
depth should be CV_8U, CV_16U or CV_32F. For larger aperture sizes it can
Parameters: only be CV_8U
• dst – The destination array; will have the same size and the same type as src
• ksize – The aperture linear size. It must be odd and more than 1, i.e. 3, 5, 7 ...
The function smoothes image using the median filter with aperture. Each
channel of a multi-channel image is processed independently. In-place operation is
supported.
morphologyEx¶
void morphologyEx(const Mat& src, Mat& dst, int op, const Mat& element, Point anchor=Point(-1, -1), int
iterations=1, int borderType=BORDER_CONSTANT, const Scalar&
borderValue=morphologyDefaultBorderValue())¶
o MORPH_OPEN - opening
Parameters:
o MORPH_CLOSE - closing
o MORPH_GRADIENT - morphological gradient
o MORPH_TOPHAT - “top hat”
o MORPH_BLACKHAT - “black hat”
• iterations – Number of times erosion and dilation are applied
• borderType – The pixel extrapolation method; see borderInterpolate
• borderValue – The border value in case of a constant border. The default
value has a special meaning, see createMorphoogyFilter
The function can perform advanced morphological transformations using erosion and
dilation as basic operations.
Opening:
Closing:
Morphological gradient:
“Top hat”:
“Black hat”:
Laplacian¶
void Laplacian(const Mat& src, Mat& dst, int ddepth, int ksize=1, double scale=1, double delta=0, int
borderType=BORDER_DEFAULT)¶
The function calculates the Laplacian of the source image by adding up the second x and y
derivatives calculated using the Sobel operator:
This is done when ksize > 1. When ksize == 1, the Laplacian is computed by filtering
the image with the following aperture:
See also: Sobel, Scharr
pyrDown¶
void pyrDown(const Mat& src, Mat& dst, const Size& dstsize=Size())¶
The function performs the downsampling step of the Gaussian pyramid construction. First it
convolves the source image with the kernel:
and then downsamples the image by rejecting even rows and columns.
pyrUp¶
void pyrUp(const Mat& src, Mat& dst, const Size& dstsize=Size())¶
The function performs the upsampling step of the Gaussian pyramid construction (it can
actually be used to construct the Laplacian pyramid). First it upsamples the source image by
injecting even zero rows and columns and then convolves the result with the same kernel as
in pyrDown, multiplied by 4.
sepFilter2D¶
void sepFilter2D(const Mat& src, Mat& dst, int ddepth, const Mat& rowKernel, const Mat&
columnKernel, Point anchor=Point(-1, -1), double delta=0, int borderType=BORDER_DEFAULT)¶
The function applies a separable linear filter to the image. That is, first, every row of src is
filtered with 1D kernel rowKernel. Then, every column of the result is filtered with 1D
kernel columnKernel and the final result shifted by delta is stored in dst.
Sobel¶
void Sobel(const Mat& src, Mat& dst, int ddepth, int xorder, int yorder, int ksize=3, double scale=1, double
delta=0, int borderType=BORDER_DEFAULT)¶
Calculates the first, second, third or mixed image derivatives using an extended Sobel
operator
There is also the special value ksize = CV_SCHARR (-1) that corresponds to a Scharr
filter that may give more accurate results than a Sobel. The Scharr aperture is
The function calculates the image derivative by convolving the image with the appropriate
kernel:
The Sobel operators combine Gaussian smoothing and differentiation, so the result is more
or less resistant to the noise. Most often, the function is called with (xorder = 1, yorder =
0, ksize = 3) or (xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image
derivative. The first case corresponds to a kernel of:
The function computes the first x- or y- spatial image derivative using Scharr operator. The
call
is equivalent to
In the case when the user specifies the forward mapping: , the OpenCV
functions first compute the corresponding inverse mapping: and then use
the above formula.
The actual implementations of the geometrical transformations, from the most generic remap and to
the simplest and the fastest resize, need to solve the 2 main problems with the above formula:
• extrapolation of non-existing pixels. Similarly to the filtering functions, described in the previous
section, for some one of or , or they both, may fall outside of the image,
in which case some extrapolation method needs to be used. OpenCV provides the same selection
of the extrapolation methods as in the filtering functions, but also an additional method
BORDER_TRANSPARENT, which means that the corresponding pixels in the destination image will
not be modified at all.
• interpolation of pixel values. Usually and are floating-point numbers (i.e.
can be an affine or perspective transformation, or radial lens distortion correction etc.), so
a pixel values at fractional coordinates needs to be retrieved. In the simplest case the coordinates
can be just rounded to the nearest integer coordinates and the corresponding pixel used, which is
called nearest-neighbor interpolation. However, a better result can be achieved by using more
sophisticated
bgroup({http://en.wikipedia.org/wiki/Multivariate_interpolation})bgroup({interpolation methods}),
where a polynomial function is fit into some neighborhood of the computed pixel
and then the value of the polynomial at is taken as
the interpolated pixel value. In OpenCV you can choose between several interpolation methods,
see resize.
convertMaps¶
void convertMaps(const Mat& map1, const Mat& map2, Mat& dstmap1, Mat& dstmap2, int
dstmap1type, bool nninterpolation=false)¶
The function converts a pair of maps for remap from one representation to another. The
following options ((map1.type(), map2.type()) (dstmap1.type(),
dstmap2.type())) are supported:
getAffineTransform¶
Mat getAffineTransform(const Point2f src[], const Point2f dst[])¶
where
getPerspectiveTransform¶
Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[])¶
where
See also: findHomography, warpPerspective, perspectiveTransform
getRectSubPix¶
void getRectSubPix(const Mat& image, Size patchSize, Point2f center, Mat& dst, int patchType=-1)¶
where the values of the pixels at non-integer coordinates are retrieved using bilinear
interpolation. Every channel of multiple-channel images is processed independently. While
the rectangle center must be inside the image, parts of the rectangle may be outside. In this
case, the replication border mode (see borderInterpolate) is used to extrapolate the pixel
values outside of the image.
getRotationMatrix2D¶
Mat getRotationMatrix2D(Point2f center, double angle, double scale)¶
The transformation maps the rotation center to itself. If this is not the purpose, the shift
should be adjusted.
invertAffineTransform¶
void invertAffineTransform(const Mat& M, Mat& iM)¶
remap¶
void remap(const Mat& src, Mat& dst, const Mat& map1, const Mat& map2, int interpolation, int
borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())
The function remap transforms the source image using the specified map:
Where values of pixels with non-integer coordinates are computed using one of the available
interpolation methods. and can be encoded as separate floating-point maps,
interleaved floating-point maps or fixed-point maps. The function can not operate in-place.
resize¶
void resize(const Mat& src, Mat& dst, Size dsize, double fx=0, double fy=0, int
interpolation=INTER_LINEAR)
Resizes an image
param The scale factor along the horizontal axis. When 0, it is computed as
fx:
param The scale factor along the vertical axis. When 0, it is computed as
fy:
param interpolation:
If you want to decimate the image by factor of 2 in each direction, you can call the function
this way:
// specify fx and fy and let the function to compute the destination image
size.
resize(src, dst, Size(), 0.5, 0.5, interpolation);
warpAffine¶
void warpAffine(const Mat& src, Mat& dst, const Mat& M, Size dsize, int flags=INTER_LINEAR, int
borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())¶
The function warpAffine transforms the source image using the specified matrix:
when the flag WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with
invertAffineTransform and then put in the formula above instead of M. The function can not
operate in-place.
warpPerspective¶
void warpPerspective(const Mat& src, Mat& dst, const Mat& M, Size dsize, int flags=INTER_LINEAR, int
borderMode=BORDER_CONSTANT, const Scalar& borderValue=Scalar())¶
The function warpPerspective transforms the source image using the specified matrix:
when the flag WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with
invert and then put in the formula above instead of M. The function can not operate in-place.
r
• ADAPTIVE_THRESH_GAUSSIAN_C - (
• THRESH_BINARY_INV - None
param blockSize:
The size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3,
5, 7, and so on
param The constant subtracted from the mean or weighted mean (see the discussion); normally,
C: it’s positive, but may be zero or negative as well
The function transforms a grayscale image to a binary image according to the formulas:
• THRESH_BINARY -
• THRESH_BINARY_INV -
cvtColor¶
void cvtColor(const Mat& src, Mat& dst, int code, int dstCn=0)¶
Converts image from one color space to another
The function converts the input image from one color space to another. In the case of
transformation to-from RGB color space the ordering of the channels should be specified
explicitly (RGB or BGR).
Of course, in the case of linear transformations the range does not matter, but in the non-
linear cases the input RGB image should be normalized to the proper value range in order to
get the correct results, e.g. for RGB:math:$rightarrow $`L*u*v* transformation. For
example, if you have a 32-bit floating-point image directly converted from 8-bit image
without any scaling, then it will have 0..255 value range, instead of the assumed by the
function 0..1. So, before calling :cfunc:`cvtColor(), you need first to scale the image down:
img *= 1./255;
cvtColor(img, img, CV_BGR2Luv);
• Transformations within RGB space like adding/removing the alpha channel, reversing the
channel order, conversion to/from 16-bit RGB color (R5:G6:B5 or R5:G5:B5), as well as
conversion to/from grayscale using:
and
Some more advanced channel reordering can also be done with mixChannels.
• RGB CIE XYZ.Rec 709 with D65 white point (CV_BGR2XYZ, CV_RGB2XYZ,
CV_XYZ2BGR, CV_XYZ2RGB):
, and cover the whole value range (in the case of floating-point images may exceed
1).
where
if then
On output , , .
• 8-bit images *
• 32-bit images *
H, S, V are left as is
if then On output , , .
• 8-bit images *
• 32-bit images *
H, S, V are left as is
• RGB CIE L*a*b* (CV_BGR2Lab, CV_RGB2Lab, CV_Lab2BGR, CV_Lab2RGB) in
the case of 8-bit and 16-bit images R, G and B are converted to floating-point format
and scaled to fit the 0 to 1 range
where
and
On output , ,
• 8-bit images *
• 16-bit images *
• 32-bit images *
L, a, b are left as is
• 8-bit images *
• 16-bit images *
• 32-bit images *
L, u, v are left as is
The above formulas for converting RGB to/from various color spaces have been taken from
multiple sources on Web, primarily from the Charles Poynton site
http://www.poynton.com/ColorFAQ.html
The output RGB components of a pixel are interpolated from 1, 2 or 4 neighbors of the pixel
having the same color. There are several modifications of the above pattern that can be
achieved by shifting the pattern one pixel left and/or one pixel up. The two letters and
in the conversion constants CV_Bayer 2BGR and CV_Bayer 2RGB indicate the
particular pattern type - these are components from the second row, second and third
columns, respectively. For example, the above pattern has very popular “BG” type.
distanceTransform¶
void distanceTransform(const Mat& src, Mat& dst, int distanceType, int maskSize)¶
void distanceTransform(const Mat& src, Mat& dst, Mat& labels, int distanceType, int maskSize)
Calculates the distance to the closest zero pixel for each pixel of the source image.
The functions distanceTransform calculate the approximate or precise distance from every
binary image pixel to the nearest zero pixel. (for zero image pixels the distance will
obviously be zero).
In other cases the algorithm is used, that is, for pixel the function finds the shortest path to
the nearest zero pixel consisting of basic shifts: horizontal, vertical, diagonal or knight’s
move (the latest is available for a mask). The overall distance is calculated as a sum
of these basic distances. Because the distance function should be symmetric, all of the
horizontal and vertical shifts must have the same cost (that is denoted as a), all the diagonal
shifts must have the same cost (denoted b), and all knight’s moves must have the same cost
(denoted c). For CV_DIST_C and CV_DIST_L1 types the distance is calculated precisely,
whereas for CV_DIST_L2 (Euclidian distance) the distance can be calculated only with some
relative error (a mask gives more accurate results). For a, b and c OpenCV uses the
values suggested in the original paper:
CV_DIST_C a = 1, b = 1
CV_DIST_L1 a = 1, b = 2
CV_DIST_L2 a=0.955, b=1.3693
Typically, for a fast, coarse distance estimation CV_DIST_L2, a mask is used, and for a
more accurate distance estimation CV_DIST_L2, a mask or the precise algorithm is
used. Note that both the precise and the approximate algorithms are linear on the number of
pixels.
The second variant of the function does not only compute the minimum distance for each
pixel , but it also identifies the nearest the nearest connected component consisting of
zero pixels. Index of the component is stored in . The connected components
of zero pixels are also found and marked by the function.
In this mode the complexity is still linear. That is, the function provides a very fast way to
compute Voronoi diagram for the binary image. Currently, this second variant can only use
the approximate distance transform algorithm.
floodFill¶
int floodFill(Mat& image, Point seed, Scalar newVal, Rect* rect=0, Scalar loDiff=Scalar(), Scalar
upDiff=Scalar(), int flags=4)¶
int floodFill(Mat& image, Mat& mask, Point seed, Scalar newVal, Rect* rect=0, Scalar loDiff=Scalar(),
Scalar upDiff=Scalar(), int flags=4)
The functions floodFill fill a connected component starting from the seed point with the
specified color. The connectivity is determined by the color/brightness closeness of the
neighbor pixels. The pixel at is considered to belong to the repainted domain if:
where is the value of one of pixel neighbors that is already known to belong to
the component. That is, to be added to the connected component, a pixel’s color/brightness
should be close enough to the:
• color/brightness of one of its neighbors that are already referred to the connected
component in the case of floating range
• color/brightness of the seed point in the case of fixed range.
By using these functions you can either mark a connected component with the specified
color in-place, or build a mask and then extract the contour or copy the region to another
image etc. Various modes of the function are demonstrated in floodfill.c sample.
inpaint¶
void inpaint(const Mat& src, const Mat& inpaintMask, Mat& dst, double inpaintRadius, int flags)
The function reconstructs the selected image area from the pixel near the area boundary. The
function may be used to remove dust and scratches from a scanned photo, or to remove
undesirable objects from still images or video. See http://en.wikipedia.org/wiki/Inpainting
for more details.
integral¶
void integral(const Mat& image, Mat& sum, int sdepth=-1)
void integral(const Mat& image, Mat& sum, Mat& sqsum, int sdepth=-1)
void integral(const Mat& image, Mat& sum, Mat& sqsum, Mat& tilted, int sdepth=-1)
The functions integral calculate one or more integral images for the source image as
following:
Using these integral images, one may calculate sum, mean and standard deviation over a
specific up-right or rotated rectangular region of the image in a constant time, for example:
It makes possible to do a fast blurring or fast block correlation with variable window size,
for example. In the case of multi-channel images, sums for each channel are accumulated
independently.
threshold¶
double threshold(const Mat& src, Mat& dst, double thresh, double maxVal, int thresholdType)
• THRESH_BINARY -
• THRESH_BINARY_INV -
• THRESH_TRUNC -
• THRESH_TOZERO -
• THRESH_TOZERO_INV -
Also, the special value THRESH_OTSU may be combined with one of the above values. In this
case the function determines the optimal threshold value using Otsu’s algorithm and uses it
instead of the specified thresh. The function returns the computed threshold value.
Currently, Otsu’s method is implemented only for 8-bit images.
See also: adaptiveThreshold, findContours, compare, min, max
watershed¶
void watershed(const Mat& image, Mat& markers)
Note, that it is not necessary that every two neighbor connected components are separated
by a watershed boundary (-1’s pixels), for example, in case when such tangent components
exist in the initial marker image. Visual demonstration and usage example of the function
can be found in OpenCV samples directory; see watershed.cpp demo.
Histograms¶
calcHist¶
void calcHist(const Mat* arrays, int narrays, const int* channels, const Mat& mask, MatND& hist, int
dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false)¶
void calcHist(const Mat* arrays, int narrays, const int* channels, const Mat& mask, SparseMat& hist, int
dims, const int* histSize, const float** ranges, bool uniform=true, bool accumulate=false)
• arrays – Source arrays. They all should have the same depth, CV_8U or
CV_32F, and the same size. Each of them can have an arbitrary number of
channels
• narrays – The number of source arrays
• channels – The list of dims channels that are used to compute the histogram.
The first array channels are numerated from 0 to arrays[0].channels()-
1, the second array channels are counted from arrays[0].channels() to
arrays[0].channels() + arrays[1].channels()-1 etc.
Parameter
• mask – The optional mask. If the matrix is not empty, it must be 8-bit array of
s: the same size as arrays[i]. The non-zero mask elements mark the array
elements that are counted in the histogram
• hist – The output histogram, a dense or sparse dims-dimensional array
• dims – The histogram dimensionality; must be positive and not greater than
:cmacro:`CV_MAX_DIMS`(=32 in the current OpenCV version)
• histSize – The array of histogram sizes in each dimension
• ranges – The array of dims arrays of the histogram bin boundaries in each
dimension. When the histogram is uniform (uniform``=true), then for
each dimension ``i it’s enough to specify the lower (inclusive) boundary
of the 0-th histogram bin and the upper (exclusive) boundary
for the last histogram bin histSize[i]-1. That is, in the case
of uniform histogram each of ranges[i] is an array of 2 elements. When the
histogram is not uniform (uniform=false), then each of ranges[i]
contains histSize[i]+1 elements:
. The array elements, which are not between and , are not
counted in the histogram
• uniform – Indicates whether the histogram is uniform or not, see above
• accumulate – Accumulation flag. If it is set, the histogram is not cleared in the
beginning (when it is allocated). This feature allows user to compute a single
histogram from several sets of arrays, or to update the histogram in time
The functions calcHist calculate the histogram of one or more arrays. The elements of a
tuple that is used to increment a histogram bin are taken at the same location from the
corresponding input arrays. The sample below shows how to compute 2D Hue-Saturation
histogram for a color imag
#include <cv.h>
#include <highgui.h>
Mat hsv;
cvtColor(src, hsv, CV_BGR2HSV);
namedWindow( "Source", 1 );
imshow( "Source", src );
waitKey();
}
calcBackProject¶
void calcBackProject(const Mat* arrays, int narrays, const int* channels, const MatND& hist, Mat&
backProject, const float** ranges, double scale=1, bool uniform=true)¶
void calcBackProject(const Mat* arrays, int narrays, const int* channels, const SparseMat& hist, Mat&
backProject, const float** ranges, double scale=1, bool uniform=true)
• arrays – Source arrays. They all should have the same depth, CV_8U or
CV_32F, and the same size. Each of them can have an arbitrary number of
channels
• narrays – The number of source arrays
• channels – The list of channels that are used to compute the back projection.
The number of channels must match the histogram dimensionality. The first
array channels are numerated from 0 to arrays[0].channels()-1, the
second array channels are counted from arrays[0].channels() to
Parameters:
arrays[0].channels() + arrays[1].channels()-1 etc.
• hist – The input histogram, a dense or sparse
• backProject – Destination back projection aray; will be a single-channel array
of the same size and the same depth as arrays[0]
• ranges – The array of arrays of the histogram bin boundaries in each
dimension. See calcHist
• scale – The optional scale factor for the output back projection
• uniform – Indicates whether the histogram is uniform or not, see above
The functions calcBackProject calculate the back project of the histogram. That is,
similarly to calcHist, at each location (x, y) the function collects the values from the
selected channels in the input images and finds the corresponding histogram bin. But instead
of incrementing it, the function reads the bin value, scales it by scale and stores in
backProject(x,y). In terms of statistics, the function computes probability of each
element value in respect with the empirical probability distribution represented by the
histogram. Here is how, for example, you can find and track a bright-colored object in a
scene:
• Before the tracking, show the object to the camera such that covers almost the whole
frame. Calculate a hue histogram. The histogram will likely have a strong maximums,
corresponding to the dominant colors in the object.
• During the tracking, calculate back projection of a hue plane of each input video frame
using that pre-computed histogram. Threshold the back projection to suppress weak
colors. It may also have sense to suppress pixels with non sufficient color saturation and
too dark or too bright pixels.
• Find connected components in the resulting picture and choose, for example, the largest
component.
compareHist¶
double compareHist(const MatND& H1, const MatND& H2, int method)¶
The functions compareHist compare two dense or two sparse histograms using the
specified method:
• Correlation (method=CV_COMP_CORREL) *
where
and is the total number of histogram bins.
• Chi-Square (method=CV_COMP_CHISQR) *
• Intersection (method=CV_COMP_INTERSECT) *
While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be
suitable for high-dimensional sparse histograms, where, because of aliasing and sampling
problems the coordinates of non-zero histogram bins can slightly shift. To compare such
histograms or more general sparse configurations of weighted points, consider using the
calcEMD function.
equalizeHist¶
void equalizeHist(const Mat& src, Mat& dst)¶
The function equalizes the histogram of the input image using the following algorithm:
The algorithm normalizes the brightness and increases the contrast of the image.
Feature Detection¶
Canny¶
void Canny(const Mat& image, Mat& edges, double threshold1, double threshold2, int apertureSize=3,
bool L2gradient=false)¶
The function finds edges in the input image image and marks them in the output map edges
using the Canny algorithm. The smallest value between threshold1 and threshold2 is
used for edge linking, the largest value is used to find the initial segments of strong edges,
see http://en.wikipedia.org/wiki/Canny_edge_detector
cornerEigenValsAndVecs¶
void cornerEigenValsAndVecs(const Mat& src, Mat& dst, int blockSize, int apertureSize, int
borderType=BORDER_DEFAULT)¶
After that it finds eigenvectors and eigenvalues of and stores them into destination image
in the form where
• *
• *
• *
The output of the function can be used for robust edge or corner detection.
cornerHarris¶
void cornerHarris(const Mat& src, Mat& dst, int blockSize, int apertureSize, double k, int
borderType=BORDER_DEFAULT)¶
The function runs the Harris edge detector on the image. Similarly to cornerMinEigenVal
and cornerEigenValsAndVecs, for each pixel it calculates a gradient
covariation matrix over a neighborhood. Then, it
computes the following characteristic:
Corners in the image can be found as the local maxima of this response map.
cornerMinEigenVal¶
void cornerMinEigenVal(const Mat& src, Mat& dst, int blockSize, int apertureSize=3, int
borderType=BORDER_DEFAULT)¶
The function is similar to cornerEigenValsAndVecs but it calculates and stores only the
minimal eigenvalue of the covariation matrix of derivatives, i.e. in terms of the
formulae in cornerEigenValsAndVecs description.
cornerSubPix¶
void cornerSubPix(const Mat& image, vector<Point2f>& corners, Size winSize, Size zeroZone,
TermCriteria criteria)¶
The function iterates to find the sub-pixel accurate location of corners, or radial saddle
points, as shown in on the picture below.
Sub-pixel accurate corner locator is based on the observation that every vector from the
center to a point located within a neighborhood of is orthogonal to the image gradient
at subject to image and measurement noise. Consider the expression:
where is the image gradient at the one of the points in a neighborhood of . The
value of is to be found such that is minimized. A system of equations may be set up with
set to zero:
where the gradients are summed within a neighborhood (“search window”) of . Calling the
first gradient term and the second gradient term gives:
The algorithm sets the center of the neighborhood window at this new center and then
iterates until the center keeps within a set threshold.
goodFeaturesToTrack¶
void goodFeaturesToTrack(const Mat& image, vector<Point2f>& corners, int maxCorners, double
qualityLevel, double minDistance, const Mat& mask=Mat(), int blockSize=3, bool useHarrisDetector=false,
double k=0.04)¶
The function finds the most prominent corners in the image or in the specified image region,
as described in :
• the function first calculates the corner quality measure at every source image pixel using
the cornerMinEigenVal or cornerHarris
• then it performs non-maxima suppression (the local maxima in neighborhood are
retained).
• the next step rejects the corners with the minimal eigenvalue less than
.
• the remaining corners are then sorted by the quality measure in the descending order.
• finally, the function throws away each corner if there is a stronger corner ( )
such that the distance between them is less than minDistance
HoughCircles¶
void HoughCircles(Mat& image, vector<Vec3f>& circles, int method, double dp, double minDist, double
param1=100, double param2=100, int minRadius=0, int maxRadius=0)¶
The function finds circles in a grayscale image using some modification of Hough
transform. Here is a short usage example:
#include <cv.h>
#include <highgui.h>
#include <math.h>
Note that usually the function detects the circles’ centers well, however it may fail to find
the correct radii. You can assist the function by specifying the radius range (minRadius and
maxRadius) if you know it, or you may ignore the returned radius, use only the center and
find the correct radius using some additional procedure.
HoughLines¶
void HoughLines(Mat& image, vector<Vec2f>& lines, double rho, double theta, int threshold, double
srn=0, double stn=0)¶
• image – The 8-bit, single-channel, binary source image. The image may be
modified by the function
• lines – The output vector of lines. Each line is represented by a two-element
vector . is the distance from the coordinate origin (top-left
corner of the image) and is the line rotation angle in radians (
)
• rho – Distance resolution of the accumulator in pixels
• theta – Angle resolution of the accumulator in radians
Parameters: • threshold – The accumulator threshold parameter. Only those lines are
returned that get enough votes ( )
• srn – For the multi-scale Hough transform it is the divisor for the distance
resolution rho. The coarse accumulator distance resolution will be rho and
the accurate accumulator resolution will be rho/srn. If both srn=0 and
stn=0 then the classical Hough transform is used, otherwise both these
parameters should be positive.
• stn – For the multi-scale Hough transform it is the divisor for the distance
resolution theta
The function implements standard or standard multi-scale Hough transform algorithm for
line detection. See HoughLinesP for the code example.
HoughLinesP¶
void HoughLinesP(Mat& image, vector<Vec4i>& lines, double rho, double theta, int threshold, double
minLineLength=0, double maxLineGap=0)¶
• image – The 8-bit, single-channel, binary source image. The image may be
modified by the function
• lines – The output vector of lines. Each line is represented by a 4-element
vector , where and are the ending points
of each line segment detected.
• rho – Distance resolution of the accumulator in pixels
Parameters: • theta – Angle resolution of the accumulator in radians
• threshold – The accumulator threshold parameter. Only those lines are
returned that get enough votes ( )
• minLineLength – The minimum line length. Line segments shorter than that
will be rejected
• maxLineGap – The maximum allowed gap between points on the same line to
link them.
The function implements probabilistic Hough transform algorithm for line detection,
described in . Below is line detection example:
#if 0
vector<Vec2f> lines;
HoughLines( dst, lines, 1, CV_PI/180, 100 );
waitKey(0);
return 0;
}
This is the sample picture the function parameters have been tuned for:
And this is the output of the above program in the case of probabilistic Hough transform
perCornerDetect¶
void preCornerDetect(const Mat& src, Mat& dst, int apertureSize, int borderType=BORDER_DEFAULT)¶
The function calculates the complex spatial derivative-based function of the source image
where , are the first image derivatives, , are the second image derivatives
and is the mixed derivative.
The corners can be found as local maximums of the functions, as shown below:
KeyPoint¶
Data structure for salient point detectors
KeyPoint
{
public:
// default constructor
KeyPoint();
// two complete constructors
KeyPoint(Point2f _pt, float _size, float _angle=-1,
float _response=0, int _octave=0, int _class_id=-1);
KeyPoint(float x, float y, float _size, float _angle=-1,
float _response=0, int _octave=0, int _class_id=-1);
// coordinate of the point
Point2f pt;
// feature size
float size;
// feature orintation in degrees
// (has negative value if the orientation
// is not defined/not computed)
float angle;
// feature strength
// (can be used to select only
// the most prominent key points)
float response;
// scale-space octave in which the feature has been found;
// may correlate with the size
int octave;
// point (can be used by feature
// classifiers or object detectors)
int class_id;
};
MSER¶
Maximally-Stable Extremal Region Extractor
SURF¶
Class for extracting Speeded Up Robust Features from an image.
The class SURF implements Speeded Up Robust Features descriptor . There is fast multi-scale
Hessian keypoint detector that can be used to find the keypoints (which is the default option), but
the descriptors can be also computed for the user-specified keypoints. The function can be used for
object tracking and localization, image stitching etc. See the find_obj.cpp demo in OpenCV
samples directory.
StarDetector¶
Implements Star keypoint detector
The functions accumulate* can be used, for example, to collect statistic of background of a
scene, viewed by a still camera, for the further foreground-background segmentation.
accumulateSquare¶
void accumulateSquare(const Mat& src, Mat& dst, const Mat& mask=Mat())¶
The function adds the input image src or its selected region, raised to power 2, to the
accumulator dst:
accumulateProduct¶
void accumulateProduct(const Mat& src1, const Mat& src2, Mat& dst, const Mat& mask=Mat())¶
• src1 – The first input image, 1- or 3-channel, 8-bit or 32-bit floating point
• src2 – The second input image of the same type and the same size as src1
Parameters: • dst – Accumulator with the same number of channels as input images, 32-bit
or 64-bit floating-point
• mask – Optional operation mask
The function adds the product of 2 images or their selected regions to the accumulator dst:
accumulateWeighted¶
void accumulateWeighted(const Mat& src, Mat& dst, double alpha, const Mat& mask=Mat())¶
that is, alpha regulates the update speed (how fast the accumulator “forgets” about earlier
images). The function supports multi-channel images; each channel is processed
independently.
calcOpticalFlowPyrLK¶
void calcOpticalFlowPyrLK(const Mat& prevImg, const Mat& nextImg, const vector<Point2f>&
prevPts, vector<Point2f>& nextPts, vector<uchar>& status, vector<float>& err, Size winSize=Size(15, 15), int
maxLevel=3, TermCriteria criteria=TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), double
derivLambda=0.5, int flags=0)¶
Calculates the optical flow for a sparse feature set using the iterative Lucas-Kanade method
with pyramids
calcOpticalFlowFarneback¶
void calcOpticalFlowFarneback(const Mat& prevImg, const Mat& nextImg, Mat& flow, double
pyrScale, int levels, int winsize, int iterations, int polyN, double polySigma, int flags)¶
The function finds optical flow for each prevImg pixel using the alorithm so that
updateMotionHistory¶
void updateMotionHistory(const Mat& silhouette, Mat& mhi, double timestamp, double duration)¶
• silhouette – Silhouette mask that has non-zero pixels where the motion occurs
• mhi – Motion history image, that is updated by the function (single-channel,
32-bit floating-point)
Parameters:
• timestamp – Current time in milliseconds or other units
• duration – Maximal duration of the motion track in the same units as
timestamp
That is, MHI pixels where motion occurs are set to the current timestamp, while the pixels
where motion happened last time a long time ago are cleared.
calcMotionGradient¶
void calcMotionGradient(const Mat& mhi, Mat& mask, Mat& orientation, double delta1, double
delta2, int apertureSize=3)¶
The minimal and maximal allowed difference between mhi values within
a pixel neighorhood. That is, the function finds the minimum ( )
and maximum ( ) mhi values over neighborhood of each
pixel and marks the motion orientation at as valid only if
• apertureSize – The aperture size of Sobel operator
(in fact, fastArctan and phase are used, so that the computed angle is measured in degrees
and covers the full range 0..360). Also, the mask is filled to indicate pixels where the
computed angle is valid.
calcGlobalOrientation¶
double calcGlobalOrientation(const Mat& orientation, const Mat& mask, const Mat& mhi, double
timestamp, double duration)¶
The function calculates the average motion direction in the selected region and returns the
angle between 0 degrees and 360 degrees. The average direction is computed from the
weighted orientation histogram, where a recent motion has larger weight and the motion
occurred in the past has smaller weight, as recorded in mhi.
CamShift¶
RotatedRect CamShift(const Mat& probImage, Rect& window, TermCriteria criteria)¶
meanShift¶
int meanShift(const Mat& probImage, Rect& window, TermCriteria criteria)¶
The function implements iterative object search algorithm. It takes the object back
projection on input and the initial position. The mass center in window of the back projection
image is computed and the search window center shifts to the mass center. The procedure is
repeated until the specified number of iterations criteria.maxCount is done or until the
window center shifts by less than criteria.epsilon. The algorithm is used inside
CamShift and, unlike CamShift, the search window size or orientation do not change during
the search. You can simply pass the output of calcBackProject to this function, but better
results can be obtained if you pre-filter the back projection and remove the noise (e.g. by
retrieving connected components with findContours, throwing away contours with small
area (contourArea) and rendering the remaining contours with drawContours)
KalmanFilter¶
Kalman filter class
class KalmanFilter
{
public:
KalmanFilter();newline
KalmanFilter(int dynamParams, int measureParams, int
controlParams=0);newline
void init(int dynamParams, int measureParams, int controlParams=0);newline
// predicts statePre from statePost
const Mat& predict(const Mat& control=Mat());newline
// corrects statePre based on the input measurement vector
// and stores the result to statePost.
const Mat& correct(const Mat& measurement);newline
Calculates all of the moments up to the third order of a polygon or rasterized shape.
class Moments
{
public:
Moments();
Moments(double m00, double m10, double m01, double m20, double m11,
double m02, double m30, double m21, double m12, double m03 );
Moments( const CvMoments\& moments );
operator CvMoments() const;
// spatial moments
double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03;
// central moments
double mu20, mu11, mu02, mu30, mu21, mu12, mu03;
// central normalized moments
double nu20, nu11, nu02, nu30, nu21, nu12, nu03;
};
• array – A raster image (single-channel, 8-bit or floating-point 2D array) or an
array ( or ) of 2D points (Point or Point2f)
Parameters:
• binaryImage – (For images only) If it is true, then all the non-zero image pixels
are treated as 1’s
The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape.
In case of a raster image, the spatial moments are computed as:
the central moments are computed as:
The moments of a contour are defined in the same way, but computed using Green’s
formula (see http://en.wikipedia.org/wiki/Green_theorem), therefore, because of a limited
raster resolution, the moments computed for a contour will be slightly different from the
moments computed for the same contour rasterized.
HuMoments¶
void HuMoments(const Moments& moments, double hu[7])¶
These values are proved to be invariant to the image scale, rotation, and reflection except the
seventh one, whose sign is changed by reflection. Of course, this invariance was proved
with the assumption of infinite image resolution. In case of a raster images the computed Hu
invariants for the original and transformed images will be a bit different.
findContours¶
void findContours(const Mat& image, vector<vector<Point> >& contours, vector<Vec4i>& hierarchy, int
mode, int method, Point offset=Point())¶
void findContours(const Mat& image, vector<vector<Point> >& contours, int mode, int method, Point
offset=Point())
• image – The source, an 8-bit single-channel image. Non-zero pixels are treated
as 1’s, zero pixels remain 0’s - the image is treated as binary. You can use
compare, inRange, threshold, adaptiveThreshold, Canny etc. to create a binary
image out of a grayscale or color one. The function modifies the image while
extracting the contours
• contours – The detected contours. Each contour is stored as a vector of points
• hiararchy – The optional output vector that will contain information about the
image topology. It will have as many elements as the number of contours. For
each contour contours[i], the elements hierarchy[i][0],
hiearchy[i][1], hiearchy[i][2], hiearchy[i][3] will be set to 0-
based indices in contours of the next and previous contours at the same
hierarchical level, the first child contour and the parent contour, respectively.
If for some contour i there is no next, previous, parent or nested contours, the
corresponding elements of hierarchy[i] will be negative
Parameters
• mode –
:
The contour retrieval mode
The function retrieves contours from the binary image using the algorithm . The contours
are a useful tool for shape analysis and object detection and recognition. See squares.c in
the OpenCV sample directory.
drawContours¶
void drawContours(Mat& image, const vector<vector<Point> >& contours, int contourIdx, const Scalar&
color, int thickness=1, int lineType=8, const vector<Vec4i>& hierarchy=vector<Vec4i>(), int
maxLevel=INT_MAX, Point offset=Point())¶
#include "cv.h"
#include "highgui.h"
namedWindow( "Components", 1 );
showImage( "Components", dst );
waitKey(0);
}
approxPolyDP¶
void approxPolyDP(const Mat& curve, vector<Point>& approxCurve, double epsilon, bool closed)¶
void approxPolyDP(const Mat& curve, vector<Point2f>& approxCurve, double epsilon, bool closed)
arcLength¶
double arcLength(const Mat& curve, bool closed)¶
The function computes the curve length or the closed contour perimeter.
boundingRect¶
Rect boundingRect(const Mat& points)¶
The function calculates and returns the minimal up-right bounding rectangle for the
specified point set.
estimateRigidTransform¶
Mat estimateRigidTransform(const Mat& srcpt, const Mat& dstpt, bool fullAffine)¶
The function finds the optimal affine transform (a floating-point matrix) that
approximates best the transformation from to :
when fullAffine=false.
estimateAffine3D¶
int estimateAffine3D(const Mat& srcpt, const Mat& dstpt, Mat& out, vector<uchar>& outliers, double
ransacThreshold = 3.0, double confidence = 0.99)¶
The function estimates the optimal 3D affine transformation between two 3D point sets
using RANSAC algorithm.
contourArea¶
double contourArea(const Mat& contour)¶
The function computes the contour area. Similarly to moments the area is computed using
the Green formula, thus the returned area and the number of non-zero pixels, if you draw the
contour using drawContours or fillPoly, can be different. Here is a short example:
vector<Point> contour;
contour.push_back(Point2f(0, 0));
contour.push_back(Point2f(10, 0));
contour.push_back(Point2f(10, 10));
contour.push_back(Point2f(5, 4));
convexHull¶
void convexHull(const Mat& points, vector<int>& hull, bool clockwise=false)¶
The functions find the convex hull of a 2D point set using Sklansky’s algorithm that has
or complexity (where is the number of input points), depending on
how the initial sorting is implemented (currently it is . See the OpenCV sample
convexhull.c that demonstrates the use of the different function variants.
fitEllipse¶
RotatedRect fitEllipse(const Mat& points)¶
Fits an ellipse around a set of 2D points.
The function calculates the ellipse that fits best (in least-squares sense) a set of 2D points. It
returns the rotated rectangle in which the ellipse is inscribed.
fitLine¶
void fitLine(const Mat& points, Vec4f& line, int distType, double param, double reps, double aeps)¶
void fitLine(const Mat& points, Vec6f& line, int distType, double param, double reps, double aeps)
• distType=CV_DIST_L2 *
• distType=CV_DIST_L1 *
• distType=CV_DIST_L12 *
• distType=CV_DIST_FAIR *
• distType=CV_DIST_WELSCH *
• distType=CV_DIST_HUBER *
isContourConvex¶
bool isContourConvex(const Mat& contour)¶
The function tests whether the input contour is convex or not. The contour must be simple,
i.e. without self-intersections, otherwise the function output is undefined.
minAreaRect¶
RotatedRect minAreaRect(const Mat& points)¶
The function calculates and returns the minimum area bounding rectangle (possibly rotated)
for the specified point set. See the OpenCV sample minarea.c
minEnclosingCircle¶
void minEnclosingCircle(const Mat& points, Point2f& center, float& radius)¶
The function finds the minimal enclosing circle of a 2D point set using iterative algorithm.
See the OpenCV sample minarea.c
matchShapes¶
double matchShapes(const Mat& object1, const Mat& object2, int method, double parameter=0)¶
The function compares two shapes. The 3 implemented methods all use Hu invariants (see
HuMoments) as following ( denotes object1, denotes object2):
• method=CV_CONTOUR_MATCH_I1 *
• method=CV_CONTOUR_MATCH_I2 *
• method=CV_CONTOUR_MATCH_I3 *
where
pointPolygonTest¶
double pointPolygonTest(const Mat& contour, Point2f pt, bool measureDist)¶
The function determines whether the point is inside a contour, outside, or lies on an edge (or
coincides with a vertex). It returns positive (inside), negative (outside) or zero (on an edge)
value, correspondingly. When measureDist=false, the return value is +1, -1 and 0,
respectively. Otherwise, the return value it is a signed distance between the point and the
nearest contour edge.
Here is the sample output of the function, where each image pixel is tested against the
contour.
Planar Subdivisions¶
Object Detection¶
FeatureEvaluator¶
Base class for computing feature values in cascade classifiers
class FeatureEvaluator
{
public:
// feature type
enum { HAAR = 0, LBP = 1 };
virtual ~FeatureEvaluator();
// reads parameters of the features from a FileStorage node
virtual bool read(const FileNode& node);
// returns a full copy of the feature evaluator
virtual Ptr<FeatureEvaluator> clone() const;
// returns the feature type (HAAR or LBP for now)
virtual int getFeatureType() const;
// sets the image in which to compute the features
// (called by CascadeClassifier::setImage)
virtual bool setImage(const Mat& image, Size origWinSize);
// sets window in the current image in which the features
// will be computed (called by CascadeClassifier::runAt)
virtual bool setWindow(Point p);
CascadeClassifier¶
The cascade classifier class for object detection
class CascadeClassifier
{
public:
enum { BOOST = 0 };
// default constructor
CascadeClassifier();
// load the classifier from file
CascadeClassifier(const string& filename);
// the destructor
~CascadeClassifier();
int stageType;
int featureType;
int ncategories;
Size origWinSize;
Ptr<FeatureEvaluator> feval;
Ptr<CvHaarClassifierCascade> oldCascade;
};
groupRectangles¶
void groupRectangles(vector<Rect>& rectList, int groupThreshold, double eps=0.2)¶
The function is a wrapper for a generic function partition. It clusters all the input rectangles
using the rectangle equivalence criteria, that combines rectangles that have similar sizes and
similar locations (the similarity is defined by eps). When eps=0, no clustering is done at all.
If , all the rectangles will be put in one cluster. Then, the small clusters,
containing less than or equal to groupThreshold rectangles, will be rejected. In each other
cluster the average rectangle will be computed and put into the output rectangle list.
matchTemplate¶
void matchTemplate(const Mat& image, const Mat& templ, Mat& result, int method)¶
• image – Image where the search is running; should be 8-bit or 32-bit floating-
point
• templ – Searched template; must be not greater than the source image and
have the same data type
Parameters: • result – A map of comparison results; will be single-channel 32-bit floating-
point. If image is and templ is then result will be
The function slides through image, compares the overlapped patches of size against
templ using the specified method and stores the comparison results to result. Here are the
formulas for the available comparison methods ( denotes image, template, result).
The summation is done over template and/or the image patch:
• method=CV_TM_SQDIFF *
• method=CV_TM_SQDIFF_NORMED *
• method=CV_TM_CCORR *
• method=CV_TM_CCORR_NORMED *
• method=CV_TM_CCOEFF *
where
• method=CV_TM_CCOEFF_NORMED *
After the function finishes the comparison, the best matches can be found as global
minimums (when CV_TM_SQDIFF was used) or maximums (when CV_TM_CCORR or
CV_TM_CCOEFF was used) using the minMaxLoc function. In the case of a color image,
template summation in the numerator and each sum in the denominator is done over all of
the channels (and separate mean values are used for each channel). That is, the function can
take a color template and a color image; the result will still be a single-channel image, which
is easier to analyze.
Camera Calibration and 3D Reconstruction¶
The functions in this section use the so-called pinhole camera model. That is, a scene view is
formed by projecting 3D points into the image plane using a perspective transformation.
or
Where are the coordinates of a 3D point in the world coordinate space, are the
coordinates of the projection point in pixels. is called a camera matrix, or a matrix of intrinsic
parameters. is a principal point (that is usually at the image center), and are the
focal lengths expressed in pixel-related units. Thus, if an image from camera is scaled by some
factor, all of these parameters should be scaled (multiplied/divided, respectively) by the same
factor. The matrix of intrinsic parameters does not depend on the scene viewed and, once estimated,
can be re-used (as long as the focal length is fixed (in case of zoom lens)). The joint rotation-
translation matrix is called a matrix of extrinsic parameters. It is used to describe the camera
motion around a static scene, or vice versa, rigid motion of an object in front of still camera. That is,
translates coordinates of a point to some coordinate system, fixed with respect to the
camera. The transformation above is equivalent to the following (when ):
Real lenses usually have some distortion, mostly radial distorion and slight tangential distortion. So,
the above model is extended as:
, , are radial distortion coefficients, , are tangential distortion coefficients. Higher-order
coefficients are not considered in OpenCV. In the functions below the coefficients are passed or
returned as
vector. That is, if the vector contains 4 elements, it means that . The distortion coefficients
do not depend on the scene viewed, thus they also belong to the intrinsic camera parameters. And
they remain the same regardless of the captured image resolution. That is, if, for example, a camera
has been calibrated on images of resolution, absolutely the same distortion coefficients
can be used for images of resolution from the same camera (while , , and
need to be scaled appropriately).
• Project 3D points to the image plane given intrinsic and extrinsic parameters
• Compute extrinsic parameters given intrinsic parameters, a few 3D points and their projections.
• Estimate intrinsic and extrinsic camera parameters from several views of a known calibration
pattern (i.e. every view is described by several 3D-2D point correspodences).
• Estimate the relative position and orientation of the stereo camera “heads” and compute the
rectification transformation that makes the camera optical axes parallel.
calibrateCamera¶
double calibrateCamera(const vector<vector<Point3f> >& objectPoints, const vector<vector<Point2f>
>& imagePoints, Size imageSize, Mat& cameraMatrix, Mat& distCoeffs, vector<Mat>& rvecs, vector<Mat>&
tvecs, int flags=0)¶
Finds the camera intrinsic and extrinsic parameters from several views of a calibration
pattern.
The function estimates the intrinsic camera parameters and extrinsic parameters for each of
the views. The coordinates of 3D object points and their correspondent 2D projections in
each view must be specified. That may be achieved by using an object with known geometry
and easily detectable feature points. Such an object is called a calibration rig or calibration
pattern, and OpenCV has built-in support for a chessboard as a calibration rig (see
findChessboardCorners). Currently, initialization of intrinsic parameters (when
CV_CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration
patterns (where z-coordinates of the object points must be all 0’s). 3D calibration rigs can
also be used as long as initial cameraMatrix is provided.
• First, it computes the initial intrinsic parameters (the option only available for planar
calibration patterns) or reads them from the input parameters. The distortion coefficients
are all set to zeros initially (unless some of CV_CALIB_FIX_K? are specified).
• The the initial camera pose is estimated as if the intrinsic parameters have been already
known. This is done using solvePnP
• After that the global Levenberg-Marquardt optimization algorithm is run to minimize the
reprojection error, i.e. the total sum of squared distances between the observed feature
points imagePoints and the projected (using the current estimates for camera
parameters and the poses) object points objectPoints; see projectPoints.
calibrationMatrixValues¶
void calibrationMatrixValues(const Mat& cameraMatrix, Size imageSize, double apertureWidth,
double apertureHeight, double& fovx, double& fovy, double& focalLength, Point2d& principalPoint,
double& aspectRatio)¶
composeRT¶
void composeRT(const Mat& rvec1, const Mat& tvec1, const Mat& rvec2, const Mat& tvec2, Mat& rvec3,
Mat& tvec3)¶
void composeRT(const Mat& rvec1, const Mat& tvec1, const Mat& rvec2, const Mat& tvec2, Mat& rvec3,
Mat& tvec3, Mat& dr3dr1, Mat& dr3dt1, Mat& dr3dr2, Mat& dr3dt2, Mat& dt3dr1, Mat& dt3dt1, Mat&
dt3dr2, Mat& dt3dt2)
Also, the functions can compute the derivatives of the output vectors w.r.t the input vectors
(see matMulDeriv). The functions are used inside stereoCalibrate but can also be used in
your own code where Levenberg-Marquardt or another gradient-based solver is used to
optimize a function that contains matrix multiplication.
computeCorrespondEpilines¶
void computeCorrespondEpilines(const Mat& points, int whichImage, const Mat& F, vector<Vec3f>&
lines)¶
For points in one image of a stereo pair, computes the corresponding epilines in the other
image.
For every point in one of the two images of a stereo-pair the function finds the equation of
the corresponding epipolar line in the other image.
From the fundamental matrix definition (see findFundamentalMat), line in the second
image for the point in the first image (i.e. when whichImage=1) is computed as:
Line coefficients are defined up to a scale. They are normalized, such that .
convertPointsHomogeneous¶
void convertPointsHomogeneous(const Mat& src, vector<Point3f>& dst)¶
If the output array dimensionality is larger, an extra 1 is appended to each point. Otherwise,
the input array is simply copied (with optional transposition) to the output.
decomposeProjectionMatrix¶
void decomposeProjectionMatrix(const Mat& projMatrix, Mat& cameraMatrix, Mat& rotMatrix,
Mat& transVect)¶
Decomposes the projection matrix into a rotation matrix and a camera matrix.
It optionally returns three rotation matrices, one for each axis, and the three Euler angles that
could be used in OpenGL.
drawChessboardCorners¶
void drawChessboardCorners(Mat& image, Size patternSize, const Mat& corners, bool
patternWasFound)¶
The function draws the individual chessboard corners detected as red circles if the board was
not found or as colored corners connected with lines if the board was found.
findChessboardCorners¶
bool findChessboardCorners(const Mat& image, Size patternSize, vector<Point2f>& corners, int
flags=CV_CALIB_CB_ADAPTIVE_THRESH+CV_CALIB_CB_NORMALIZE_IMAGE)¶
The function attempts to determine whether the input image is a view of the chessboard
pattern and locate the internal chessboard corners. The function returns a non-zero value if
all of the corners have been found and they have been placed in a certain order (row by row,
left to right in every row), otherwise, if the function fails to find all the corners or reorder
them, it returns 0. For example, a regular chessboard has 8 x 8 squares and 7 x 7 internal
corners, that is, points, where the black squares touch each other. The coordinates detected
are approximate, and to determine their position more accurately, the user may use the
function cornerSubPix.
Note: the function requires some white space (like a square-thick border, the wider the
better) around the board to make the detection more robust in various environment
(otherwise if there is no border and the background is dark, the outer black squares could not
be segmented properly and so the square grouping and ordering algorithm will fail).
solvePnP¶
void solvePnP(const Mat& objectPoints, const Mat& imagePoints, const Mat& cameraMatrix, const Mat&
distCoeffs, Mat& rvec, Mat& tvec, bool useExtrinsicGuess=false)¶
Parameters:
• cameraMatrix – The input camera matrix
• distCoeffs – The input 4x1, 1x4, 5x1 or 1x5 vector of distortion coefficients
. If it is NULL, all of the distortion coefficients are set to
0
• rvec – The output rotation vector (see Rodrigues) that (together with tvec)
brings points from the model coordinate system to the camera coordinate
system
• tvec – The output translation vector
The function estimates the object pose given a set of object points, their corresponding
image projections, as well as the camera matrix and the distortion coefficients. This function
finds such a pose that minimizes reprojection error, i.e. the sum of squared distances
between the observed projections imagePoints and the projected (using projectPoints)
objectPoints.
findFundamentalMat¶
Mat findFundamentalMat(const Mat& points1, const Mat& points2, vector<uchar>& status, int
method=FM_RANSAC, double param1=3., double param2=0.99)¶
Mat findFundamentalMat(const Mat& points1, const Mat& points2, int method=FM_RANSAC, double
param1=3., double param2=0.99)
Calculates the fundamental matrix from the corresponding points in two images.
• points1 – Array of N points from the first image.. The point coordinates should
be floating-point (single or double precision)
• points2 – Array of the second image points of the same size and format as
points1
• method –
where is fundamental matrix, and are corresponding points in the first and the
second images, respectively.
The function calculates the fundamental matrix using one of four methods listed above and
returns the found fundamental matrix. Normally just 1 matrix is found, but in the case of 7-
point algorithm the function may return up to 3 solutions ( matrix that stores all 3
matrices sequentially).
Mat fundamental_matrix =
findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99);
findHomography¶
Mat findHomography(const Mat& srcPoints, const Mat& dstPoints, Mat& status, int method=0, double
ransacReprojThreshold=0)¶
Mat findHomography(const Mat& srcPoints, const Mat& dstPoints, vector<uchar>& status, int method=0,
double ransacReprojThreshold=0)
Mat findHomography(const Mat& srcPoints, const Mat& dstPoints, int method=0, double
ransacReprojThreshold=0)
param srcPoints:
param ransacReprojThreshold:
The maximum allowed reprojection error to treat a point pair as an inlier (used in the
RANSAC method only). That is, if
then the point is considered an outlier. If srcPoints and dstPoints are measured in pixels, it
usually makes sense to set this parameter somewhere in the range 1 to 10.
param The optional output mask set by a robust method (CV_RANSAC or CV_LMEDS). Note
status: that the input mask values are ignored.
The functions find and return the perspective transformation between the source and the
destination planes:
is minimized. If the parameter method is set to the default value 0, the function uses all the
point pairs to compute the initial homography estimate with a simple least-squares scheme.
However, if not all of the point pairs ( , ) fit the rigid perspective
transformation (i.e. there are some outliers), this initial estimate will be poor. In this case
one can use one of the 2 robust methods. Both methods, RANSAC and LMeDS, try many
different random subsets of the corresponding point pairs (of 4 pairs each), estimate the
homography matrix using this subset and a simple least-square algorithm and then compute
the quality/goodness of the computed homography (which is the number of inliers for
RANSAC or the median re-projection error for LMeDs). The best subset is then used to
produce the initial estimate of the homography matrix and the mask of inliers/outliers.
Regardless of the method, robust or not, the computed homography matrix is refined further
(using inliers only in the case of a robust method) with the Levenberg-Marquardt method in
order to reduce the re-projection error even more.
The method RANSAC can handle practically any ratio of outliers, but it needs the threshold to
distinguish inliers from outliers. The method LMeDS does not need any threshold, but it
works correctly only when there are more than 50% of inliers. Finally, if you are sure in the
computed features, where can be only some small noise present, but no outliers, the default
method could be the best choice.
The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is
determined up to a scale, thus it is normalized so that .
getDefaultNewCameraMatrix¶
Mat getDefaultNewCameraMatrix(const Mat& cameraMatrix, Size imgSize=Size(), bool
centerPrincipalPoint=false)¶
The function returns the camera matrix that is either an exact copy of the input
cameraMatrix (when centerPrinicipalPoint=false), or the modified one (when
``centerPrincipalPoint``=true).
getOptimalNewCameraMatrix¶
Mat getOptimalNewCameraMatrix(const Mat& cameraMatrix, const Mat& distCoeffs, Size imageSize,
double alpha, Size newImgSize=Size(), Rect* validPixROI=0)¶
Returns the new camera matrix based on the free scaling parameter
The function computes and returns the optimal new camera matrix based on the free scaling
parameter. By varying this parameter the user may retrieve only sensible pixels alpha=0,
keep all the original image pixels if there is valuable information in the corners alpha=1, or
get something in between. When alpha>0, the undistortion result will likely have some
black pixels corresponding to “virtual” pixels outside of the captured distorted image. The
original camera matrix, distortion coefficients, the computed new camera matrix and the
bgroup({newImageSize}) should be passed to initUndistortRectifyMap to produce the maps
for remap.
initCameraMatrix2D¶
Mat initCameraMatrix2D(const vector<vector<Point3f> >& objectPoints, const vector<vector<Point2f>
>& imagePoints, Size imageSize, double aspectRatio=1.)¶
Finds the initial camera matrix from the 3D-2D point correspondences
The function estimates and returns the initial camera matrix for camera calibration process.
Currently, the function only supports planar calibration patterns, i.e. patterns where each
object point has z-coordinate =0.
initUndistortRectifyMap¶
void initUndistortRectifyMap(const Mat& cameraMatrix, const Mat& distCoeffs, const Mat& R,
const Mat& newCameraMatrix, Size size, int m1type, Mat& map1, Mat& map2)¶
The function computes the joint undistortion+rectification transformation and represents the
result in the form of maps for remap. The undistorted image will look like the original, as if
it was captured with a camera with camera matrix =newCameraMatrix and zero distortion.
In the case of monocular camera newCameraMatrix is usually equal to cameraMatrix, or it
can be computed by getOptimalNewCameraMatrix for a better control over scaling. In the
case of stereo camera newCameraMatrix is normally set to P1 or P2 computed by
stereoRectify.
Also, this new camera will be oriented differently in the coordinate space, according to R.
That, for example, helps to align two heads of a stereo camera so that the epipolar lines on
both images become horizontal and have the same y- coordinate (in the case of horizontally
aligned stereo camera).
The function actually builds the maps for the inverse mapping algorithm that is used by
remap. That is, for each pixel in the destination (corrected and rectified) image the
function computes the corresponding coordinates in the source image (i.e. in the original
image from camera). The process is the following:
In the case of a stereo camera this function is called twice, once for each camera head, after
stereoRectify, which in its turn is called after stereoCalibrate. But if the stereo camera was
not calibrated, it is still possible to compute the rectification transformations directly from
the fundamental matrix using stereoRectifyUncalibrated. For each camera the function
computes homography H as the rectification transformation in pixel domain, not a rotation
matrix R in 3D space. The R can be computed from H as
matMulDeriv¶
void matMulDeriv(const Mat& A, const Mat& B, Mat& dABdA, Mat& dABdB)¶
Computes partial derivatives of the matrix product w.r.t each multiplied matrix
The function computes the partial derivatives of the elements of the matrix product
w.r.t. the elements of each of the two input matrices. The function is used to compute
Jacobian matrices in stereoCalibrate, but can also be used in any other similar optimization
function.
projectPoints¶
void projectPoints(const Mat& objectPoints, const Mat& rvec, const Mat& tvec, const Mat&
cameraMatrix, const Mat& distCoeffs, vector<Point2f>& imagePoints)¶
void projectPoints(const Mat& objectPoints, const Mat& rvec, const Mat& tvec, const Mat&
cameraMatrix, const Mat& distCoeffs, vector<Point2f>& imagePoints, Mat& dpdrot, Mat& dpdt, Mat&
dpdf, Mat& dpdc, Mat& dpddist, double aspectRatio=0)
• objectPoints – The array of object points, 3xN or Nx3 1-channel or 1xN or Nx1
3-channel (or vector<Point3f>), where N is the number of points in the
view
• rvec – The rotation vector, see Rodrigues
• tvec – The translation vector
The function computes projections of 3D points to the image plane given intrinsic and
extrinsic camera parameters. Optionally, the function computes jacobians - matrices of
partial derivatives of image points coordinates (as functions of all the input parameters) with
respect to the particular parameters, intrinsic and/or extrinsic. The jacobians are used during
the global optimization in calibrateCamera, solvePnP and stereoCalibrate. The function
itself can also used to compute re-projection error given the current intrinsic and extrinsic
parameters.
The matrix Q can be arbitrary matrix, e.g. the one computed by stereoRectify. To
reproject a sparse set of points bgroup({(x,y,d),...}) to 3D space, use perspectiveTransform.
RQDecomp3x3¶
void RQDecomp3x3(const Mat& M, Mat& R, Mat& Q)¶
Vec3d RQDecomp3x3(const Mat& M, Mat& R, Mat& Q, Mat& Qx, Mat& Qy, Mat& Qz)
The function computes a RQ decomposition using the given rotations. This function is used
in decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix
into a camera and a rotation matrix.
It optionally returns three rotation matrices, one for each axis, and the three Euler angles (as
the return value) that could be used in OpenGL.
Rodrigues¶
void Rodrigues(const Mat& src, Mat& dst)¶
• src – The input rotation vector (3x1 or 1x3) or rotation matrix (3x3)
• dst – The output rotation matrix (3x3) or rotation vector (3x1 or 1x3),
Parameters: respectively
• jacobian – Optional output Jacobian matrix, 3x9 or 9x3 - partial derivatives of
the output array components with respect to the input array components
StereoBM¶
The class for computing stereo correspondence using block matching algorithm.
StereoBM();
// the preset is one of ..._PRESET above.
// ndisparities is the size of disparity range,
// in which the optimal disparity at each pixel is searched for.
// SADWindowSize is the size of averaging window used to match pixel blocks
// (larger values mean better robustness to noise, but yield blurry
disparity maps)
StereoBM(int preset, int ndisparities=0, int SADWindowSize=21);
// separate initialization function
void init(int preset, int ndisparities=0, int SADWindowSize=21);
// computes the disparity for the two rectified 8-bit single-channel images.
// the disparity will be 16-bit singed image of the same size as left.
void operator()( const Mat& left, const Mat& right, Mat& disparity );
Ptr<CvStereoBMState> state;
};
stereoCalibrate¶
double stereoCalibrate(const vector<vector<Point3f> >& objectPoints, const vector<vector<Point2f>
>& imagePoints1, const vector<vector<Point2f> >& imagePoints2, Mat& cameraMatrix1, Mat& distCoeffs1,
Mat& cameraMatrix2, Mat& distCoeffs2, Size imageSize, Mat& R, Mat& T, Mat& E, Mat& F, TermCriteria
criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6), int flags=CALIB_FIX_INTRINSIC)¶
, . If any of CV_CALIB_FIX_K1,
CV_CALIB_FIX_K2 or CV_CALIB_FIX_K3 is specified, then the
corresponding elements of the distortion coefficients must be initialized.
• imageSize – Size of the image, used only to initialize intrinsic camera matrix.
• R – The output rotation matrix between the 1st and the 2nd cameras’
coordinate systems.
• T – The output translation vector between the cameras’ coordinate systems.
• E – The output essential matrix.
• F – The output fundamental matrix.
• criteria – The termination criteria for the iterative optimiziation algorithm.
• flags –
is fixed.
o CV_CALIB_SAME_FOCAL_LENGTH - Enforces and
The function estimates transformation between the 2 cameras making a stereo pair. If we
have a stereo camera, where the relative position and orientatation of the 2 cameras is fixed,
and if we computed poses of an object relative to the fist camera and to the second camera,
(R1, T1) and (R2, T2), respectively (that can be done with solvePnP), obviously, those
poses will relate to each other, i.e. given ( , ) it should be possible to compute ( , )
- we only need to know the position and orientation of the 2nd camera relative to the 1st
camera. That’s what the described function does. It computes ( , ) such that:
Similarly to calibrateCamera, the function minimizes the total re-projection error for all the
points in all the available views from both cameras. The function returns the final value of
the re-projection error.
stereoRectify¶
void stereoRectify(const Mat& cameraMatrix1, const Mat& distCoeffs1, const Mat& cameraMatrix2,
const Mat& distCoeffs2, Size imageSize, const Mat& R, const Mat& T, Mat& R1, Mat& R2, Mat& P1, Mat&
P2, Mat& Q, int flags=CALIB_ZERO_DISPARITY)¶
void stereoRectify(const Mat& cameraMatrix1, const Mat& distCoeffs1, const Mat& cameraMatrix2,
const Mat& distCoeffs2, Size imageSize, const Mat& R, const Mat& T, Mat& R1, Mat& R2, Mat& P1, Mat&
P2, Mat& Q, double alpha, Size newImageSize=Size(), Rect* roi1=0, Rect* roi2=0, int
flags=CALIB_ZERO_DISPARITY)
The function computes the rotation matrices for each camera that (virtually) make both
camera image planes the same plane. Consequently, that makes all the epipolar lines parallel
and thus simplifies the dense stereo correspondence problem. On input the function takes the
matrices computed by stereoCalibrate and on output it gives 2 rotation matrices and also 2
projection matrices in the new coordinates. The 2 cases are distinguished by the function
are:
• Horizontal stereo, when 1st and 2nd camera views are shifted relative to each other mainly
along the x axis (with possible small vertical shift). Then in the rectified images the
corresponding epipolar lines in left and right cameras will be horizontal and have the same
y-coordinate. P1 and P2 will look as:
• Vertical stereo, when 1st and 2nd camera views are shifted relative to each other mainly in
vertical direction (and probably a bit in the horizontal direction too). Then the epipolar
lines in the rectified images will be vertical and have the same x coordinate. P2 and P2 will
look as:
where is vertical shift between the cameras and if CALIB_ZERO_DISPARITY is
set.
As you can see, the first 3 columns of P1 and P2 will effectively be the new “rectified”
camera matrices. The matrices, together with R1 and R2, can then be passed to
initUndistortRectifyMap to initialize the rectification map for each camera.
Below is the screenshot from stereo_calib.cpp sample. Some red horizontal lines, as you
can see, pass through the corresponding image regions, i.e. the images are well rectified
(which is what most stereo correspondence algorithms rely on). The green rectangles are
roi1 and roi2 - indeed, their interior are all valid pixels.
stereoRectifyUncalibrated¶
bool stereoRectifyUncalibrated(const Mat& points1, const Mat& points2, const Mat& F, Size
imgSize, Mat& H1, Mat& H2, double threshold=5)¶
Note that while the algorithm does not need to know the intrinsic parameters of the cameras,
it heavily depends on the epipolar geometry. Therefore, if the camera lenses have significant
distortion, it would better be corrected before computing the fundamental matrix and calling
this function. For example, distortion coefficients can be estimated for each head of stereo
camera separately by using calibrateCamera and then the images can be corrected using
undistort, or just the point coordinates can be corrected with undistortPoints.
undistort¶
void undistort(const Mat& src, Mat& dst, const Mat& cameraMatrix, const Mat& distCoeffs, const Mat&
newCameraMatrix=Mat())
The function transforms the image to compensate radial and tangential lens distortion.
Those pixels in the destination image, for which there is no correspondent pixels in the
source image, are filled with 0’s (black color).
The particular subset of the source image that will be visible in the corrected image can be
regulated by newCameraMatrix. You can use getOptimalNewCameraMatrix to compute the
appropriate newCameraMatrix, depending on your requirements.
The camera matrix and the distortion parameters can be determined using calibrateCamera.
If the resolution of images is different from the used at the calibration stage, and
need to be scaled accordingly, while the distortion coefficients remain the same.
undistortPoints¶
void undistortPoints(const Mat& src, vector<Point2f>& dst, const Mat& cameraMatrix, const Mat&
distCoeffs, const Mat& R=Mat(), const Mat& P=Mat())¶
void undistortPoints(const Mat& src, Mat& dst, const Mat& cameraMatrix, const Mat& distCoeffs,
const Mat& R=Mat(), const Mat& P=Mat())
Computes the ideal point coordinates from the observed point coordinates.
where undistort() is approximate iterative algorithm that estimates the normalized original
point coordinates out of the normalized distorted point coordinates (“normalized” means
that the coordinates do not depend on the camera matrix).
The function can be used both for a stereo camera head or for monocular camera (when R is
empty).
User Interface¶
createTrackbar¶
int createTrackbar(const string& trackbarname, const string& winname, int* value, int count,
TrackbarCallback onChange CV_DEFAULT(0), void* userdata CV_DEFAULT(0))¶
The function createTrackbar creates a trackbar (a.k.a. slider or range control) with the
specified name and range, assigns a variable value to be syncronized with trackbar position
and specifies a callback function onChange to be called on the trackbar position change. The
created trackbar is displayed on the top of the given window.
getTrackbarPos¶
int getTrackbarPos(const string& trackbarname, const string& winname)¶
imshow¶
void imshow(const string& winname, const Mat& image)
The function imshow displays the image in the specified window. If the window was created
with the CV_WINDOW_AUTOSIZE flag then the image is shown with its original size, otherwise
the image is scaled to fit in the window. The function may scale the image, depending on its
depth:
namedWindow¶
void namedWindow(const string& winname, int flags)¶
Creates a window.
• name – Name of the window in the window caption that may be used as a
window identifier.
• flags – Flags of the window. Currently the only supported flag is
Parameters:
CV_WINDOW_AUTOSIZE. If this is set, the window size is automatically
adjusted to fit the displayed image (see imshow), and the user can not change
the window size manually.
The function namedWindow creates a window which can be used as a placeholder for images
and trackbars. Created windows are referred to by their names.
If a window with the same name already exists, the function does nothing.
setTrackbarPos¶
void setTrackbarPos(const string& trackbarname, const string& winname, int pos)¶
The function sets the position of the specified trackbar in the specified window.
waitKey¶
int waitKey(int delay=0)¶
Parameter: delay – Delay in milliseconds. 0 is the special value that means “forever”
The function waitKey waits for key event infinitely (when ) or for delay
milliseconds, when it’s positive. Returns the code of the pressed key or -1 if no key was
pressed before the specified time had elapsed.
Note: This function is the only method in HighGUI that can fetch and handle events, so it
needs to be called periodically for normal event processing, unless HighGUI is used within
some environment that takes care of event processing.
The function reads image from the specified buffer in memory. If the buffer is too short or
contains invalid data, the empty matrix will be returned.
See imread for the list of supported formats and the flags description.
imencode¶
bool imencode(const string& ext, const Mat& img, vector<uchar>& buf, const vector<int>&
params=vector<int>())
The function compresses the image and stores it in the memory buffer, which is resized to fit
the result. See imwrite for the list of supported formats and the flags description.
imread¶
Mat imread(const string& filename, int flags=1)
The function imread loads an image from the specified file and returns it. If the image can
not be read (because of missing file, improper permissions, unsupported or invalid format),
the function returns empty matrix (Mat::data==NULL).Currently, the following file formats
are supported:
Note1: The function determines type of the image by the content, not by the file extension.
Note2: On Windows and MacOSX the shipped with OpenCV image codecs (libjpeg, libpng,
libtiff and libjasper) are used by default; so OpenCV can always read JPEGs, PNGs and
TIFFs. On MacOSX there is also the option to use native MacOSX image readers. But
beware that currently these native image loaders give images with somewhat different pixel
values, because of the embedded into MacOSX color management.
On Linux, BSD flavors and other Unix-like open-source operating systems OpenCV looks
for the supplied with OS image codecs. Please, install the relevant packages (do not forget
the development files, e.g. “libjpeg-dev” etc. in Debian and Ubuntu) in order to get the
codec support, or turn on OPENCV_BUILD_3RDPARTY_LIBS flag in CMake.
imwrite¶
bool imwrite(const string& filename, const Mat& img, const vector<int>& params=vector<int>())
The function imwrite saves the image to the specified file. The image format is chosen
based on the filename extension, see imread for the list of extensions. Only 8-bit (or 16-bit
in the case of PNG, JPEG 2000 and TIFF) single-channel or 3-channel (with ‘BGR’ channel
order) images can be saved using this function. If the format, depth or channel order is
different, use Mat::convertTo, and cvtColor to convert it before saving, or use the universal
XML I/O functions to save the image to XML or YAML format.
VideoCapture¶
Class for video capturing from video files or cameras
class VideoCapture
{
public:
// the default constructor
VideoCapture();
// the constructor that opens video file
VideoCapture(const string& filename);
// the constructor that starts streaming from the camera
VideoCapture(int device);
// the destructor
virtual ~VideoCapture();
protected:
...
};
The class provides C++ video capturing API. Here is how the class can be used:
#include "cv.h"
#include "highgui.h"
Mat edges;
namedWindow("edges",1);
for(;;)
{
Mat frame;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_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;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return 0;
}
VideoWriter¶
Video writer class
class VideoWriter
{
public:
// default constructor
VideoWriter();
// constructor that calls open
VideoWriter(const string& filename, int fourcc,
double fps, Size frameSize, bool isColor=true);
// the destructor
virtual ~VideoWriter();
protected:
...
};
Statistical Models¶
CvStatModel¶
Base class for the statistical models in ML.
class CvStatModel
{
public:
/* CvStatModel(); */
/* CvStatModel( const CvMat* train_data ... ); */
virtual ~CvStatModel();
/* virtual bool train( const CvMat* train_data, [int tflag,] ..., const
CvMat* responses, ...,
[const CvMat* var_idx,] ..., [const CvMat* sample_idx,] ...
[const CvMat* var_type,] ..., [const CvMat* missing_mask,]
<misc_training_alg_params> ... )=0;
*/
virtual void save( const char* filename, const char* name=0 )=0;
virtual void load( const char* filename, const char* name=0 )=0;
In this declaration some methods are commented off. Actually, these are methods for which there is
no unified API (with the exception of the default constructor), however, there are many similarities
in the syntax and semantics that are briefly described below in this section, as if they are a part of
the base class.
CvStatModel::CvStatModel¶
CvStatModel::CvStatModel()¶
Default constructor.
Each statistical model class in ML has a default constructor without parameters. This
constructor is useful for 2-stage model construction, when the default constructor is
followed by train() or load().
CvStatModel::CvStatModel(...)¶
CvStatModel::CvStatModel(const CvMat* train_data ...)
Training constructor.
Most ML classes provide single-step construct and train constructors. This constructor is
equivalent to the default constructor, followed by the train() method with the parameters
that are passed to the constructor.
CvStatModel::CvStatModel¶
CvStatModel::~ CvStatModel()¶
Virtual destructor.
The destructor of the base class is declared as virtual, so it is safe to write the following
code:
CvStatModel* model;
if( use\_svm )
model = new CvSVM(... /* SVM params */);
else
model = new CvDTree(... /* Decision tree params */);
...
delete model;
Normally, the destructor of each derived class does nothing, but in this instance it calls the
overridden method clear() that deallocates all the memory.
CvStatModel::clear¶
void CvStatModel::clear()¶
The method clear does the same job as the destructor; it deallocates all the memory
occupied by the class members. But the object itself is not destructed, and can be reused
further. This method is called from the destructor, from the train methods of the derived
classes, from the methods load(), read() or even explicitly by the user.
CvStatModel::save¶
void CvStatModel::save(const char* filename, const char* name=0)¶
The method save stores the complete model state to the specified XML or YAML file with
the specified name or default name (that depends on the particular class). Data
persistence functionality from CxCore is used.
CvStatModel::load¶
void CvStatModel::load(const char* filename, const char* name=0)¶
The method load loads the complete model state with the specified name (or default model-
dependent name) from the specified XML or YAML file. The previous model state is
cleared by clear().
Note that the method is virtual, so any model can be loaded using this virtual method.
However, unlike the C types of OpenCV that can be loaded using the generic
crossbgroup({cvLoad}), here the model type must be known, because an empty model must
be constructed beforehand. This limitation will be removed in the later ML versions.
CvStatModel::write¶
void CvStatModel::write(CvFileStorage* storage, const char* name)¶
The method write stores the complete model state to the file storage with the specified
name or default name (that depends on the particular class). The method is called by
save().
CvStatModel::read¶
void CvStatMode::read(CvFileStorage* storage, CvFileNode* node)¶
The method read restores the complete model state from the specified node of the file
storage. The node must be located by the user using the function GetFileNodeByName.
CvStatModel::train¶
bool CvStatMode::train(const CvMat* train_data, [int tflag, ] ..., const CvMat* responses, ..., [const
CvMat* var_idx, ] ..., [const CvMat* sample_idx, ] ... [const CvMat* var_type, ] ..., [const CvMat*
missing_mask, ] <misc_training_alg_params> ...)¶
The method trains the statistical model using a set of input feature vectors and the
corresponding output values (responses). Both input and output vectors/values are passed as
matrices. By default the input feature vectors are stored as train_data rows, i.e. all the
components (features) of a training vector are stored continuously. However, some
algorithms can handle the transposed representation, when all values of each particular
feature (component/input variable) over the whole input set are stored continuously. If both
layouts are supported, the method includes tflag parameter that specifies the orientation:
For classification problems the responses are discrete class labels; for regression problems
the responses are values of the function to be approximated. Some algorithms can deal only
with classification problems, some - only with regression problems, and some can deal with
both problems. In the latter case the type of output variable is either passed as separate
parameter, or as a last element of var_type vector:
• CV_VAR_CATEGORICAL means that the output values are discrete class labels,
• CV_VAR_ORDERED(=CV_VAR_NUMERICAL) means that the output values are ordered, i.e.
2 different values can be compared as numbers, and this is a regression problem
The types of input variables can be also specified using var_type. Most algorithms can
handle only ordered input variables.
Many models in the ML may be trained on a selected feature subset, and/or on a selected
sample subset of the training set. To make it easier for the user, the method train usually
includes var_idx and sample_idx parameters. The former identifies variables (features) of
interest, and the latter identifies samples of interest. Both vectors are either integer
(CV_32SC1) vectors, i.e. lists of 0-based indices, or 8-bit (CV_8UC1) masks of active
variables/samples. The user may pass NULL pointers instead of either of the arguments,
meaning that all of the variables/samples are used for training.
Additionally some algorithms can handle missing measurements, that is when certain
features of certain training samples have unknown values (for example, they forgot to
measure a temperature of patient A on Monday). The parameter missing_mask, an 8-bit
matrix the same size as train_data, is used to mark the missed values (non-zero elements
of the mask).
Usually, the previous model state is cleared by clear() before running the training
procedure. However, some algorithms may optionally update the model state with the new
training data, instead of resetting it.
CvStatModel::predict¶
float CvStatMode::predict(const CvMat* sample[, <prediction_params>]) const¶
The method is used to predict the response for a new sample. In the case of classification the
method returns the class label, in the case of regression - the output function value. The
input sample must have as many components as the train_data passed to train contains.
If the var_idx parameter is passed to train, it is remembered and then is used to extract
only the necessary components from the input sample in the method predict.
The suffix “const” means that prediction does not affect the internal model state, so the
method can be safely called from within different threads.
Normal Bayes Classifier¶
This is a simple classification model assuming that feature vectors from each class are normally
distributed (though, not necessarily independently distributed), so the whole data distribution
function is assumed to be a Gaussian mixture, one component per class. Using the training data the
algorithm estimates mean vectors and covariance matrices for every class, and then it uses them for
prediction.
[Fukunaga90] K. Fukunaga. Introduction to Statistical Pattern Recognition. second ed., New York:
Academic Press, 1990.
CvNormalBayesClassifier¶
Bayes classifier for normally distributed data.
CvNormalBayesClassifier::train¶
bool CvNormalBayesClassifier::train(const CvMat* _train_data, const CvMat* _responses, const
CvMat* _var_idx =0, const CvMat* _sample_idx=0, bool update=false)¶
The method trains the Normal Bayes classifier. It follows the conventions of the generic
train “method” with the following limitations: only CV_ROW_SAMPLE data layout is
supported; the input variables are all ordered; the output variable is categorical (i.e. elements
of _responses must be integer numbers, though the vector may have CV_32FC1 type), and
missing measurements are not supported.
In addition, there is an update flag that identifies whether the model should be trained from
scratch (update=false) or should be updated using the new training data (update=true).
CvNormalBayesClassifier::predict¶
float CvNormalBayesClassifier::predict(const CvMat* samples, CvMat* results=0) const¶
The method predict estimates the most probable classes for the input vectors. The input
vectors (one or more) are stored as rows of the matrix samples. In the case of multiple input
vectors, there should be one output vector results. The predicted class for a single input
vector is returned by the method.
K Nearest Neighbors¶
The algorithm caches all of the training samples, and predicts the response for a new sample by analyzing a
certain number (K) of the nearest neighbors of the sample (using voting, calculating weighted sum etc.) The
method is sometimes referred to as “learning by example”, because for prediction it looks for the feature
vector with a known response that is closest to the given vector.
CvKNearest¶
K Nearest Neighbors model.
CvKNearest();
virtual ~CvKNearest();
protected:
...
};
CvKNearest::train¶
bool CvKNearest::train(const CvMat* _train_data, const CvMat* _responses, const CvMat*
_sample_idx=0, bool is_regression=false, int _max_k=32, bool _update_base=false)¶
The method trains the K-Nearest model. It follows the conventions of generic train
“method” with the following limitations: only CV_ROW_SAMPLE data layout is
supported, the input variables are all ordered, the output variables can be either categorical
(is_regression=false) or ordered (is_regression=true), variable subsets (var_idx)
and missing measurements are not supported.
The parameter _max_k specifies the number of maximum neighbors that may be passed to
the method find_nearest.
The parameter _update_base specifies whether the model is trained from scratch
(_update_base=false), or it is updated using the new training data (_update_base=true).
In the latter case the parameter _max_k must not be larger than the original value.
CvKNearest::find_nearest¶
float CvKNearest::find_nearest(const CvMat* _samples, int k, CvMat* results=0, const float**
neighbors=0, CvMat* neighbor_responses=0, CvMat* dist=0) const¶
For each input vector (which are the rows of the matrix _samples) the method finds the
nearest neighbor. In the case of regression, the predicted result will
be a mean value of the particular vector’s neighbor responses. In the case of classification
the class is determined by voting.
For custom classification/regression prediction, the method can optionally return pointers to
the neighbor vectors themselves (neighbors, an array of k*_samples->rows pointers),
their corresponding output values (neighbor_responses, a vector of k*_samples->rows
elements) and the distances from the input vectors to the neighbors (dist, also a vector of
k*_samples->rows elements).
For each input vector the neighbors are sorted by their distances to the vector.
If only a single input vector is passed, all output matrices are optional and the predicted
value is returned by the method.
// learn classifier
CvKNearest knn( trainData, trainClasses, 0, false, K );
CvMat* nearests = cvCreateMat( 1, K, CV_32FC1);
cvReleaseMat( &trainClasses );
cvReleaseMat( &trainData );
return 0;
}
The solution is optimal in a sense that the margin between the separating hyper-plane and the
nearest feature vectors from the both classes (in the case of 2-class classifier) is maximal. The
feature vectors that are the closest to the hyper-plane are called “support vectors”, meaning that the
position of other vectors does not affect the hyper-plane (the decision function).
There are a lot of good references on SVM. Here are only a few ones to start with.
• [Burges98] C. Burges. “A tutorial on support vector machines for pattern recognition”, Knowledge
Discovery and Data Mining 2(2), 1998. (available online at
http://citeseer.ist.psu.edu/burges98tutorial.html).
• LIBSVM - A Library for Support Vector Machines. By Chih-Chung Chang and Chih-Jen Lin
(http://www.csie.ntu.edu.tw/cjlin/libsvm/)
CvSVM¶
Support Vector Machines.
CvSVM();
virtual ~CvSVM();
protected:
...
};
CvSVMParams¶
SVM training parameters.
struct CvSVMParams
{
CvSVMParams();
CvSVMParams( int _svm_type, int _kernel_type,
double _degree, double _gamma, double _coef0,
double _C, double _nu, double _p,
CvMat* _class_weights, CvTermCriteria _term_crit );
int svm_type;
int kernel_type;
double degree; // for poly
double gamma; // for poly/rbf/sigmoid
double coef0; // for poly/sigmoid
double C; // for CV_SVM_C_SVC, CV_SVM_EPS_SVR and CV_SVM_NU_SVR
double nu; // for CV_SVM_NU_SVC, CV_SVM_ONE_CLASS, and CV_SVM_NU_SVR
double p; // for CV_SVM_EPS_SVR
CvMat* class_weights; // for CV_SVM_C_SVC
CvTermCriteria term_crit; // termination criteria
};
The structure must be initialized and passed to the training method of CvSVM.
CvSVM::train¶
bool CvSVM::train(const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx=0, const
CvMat* _sample_idx=0, CvSVMParams _params=CvSVMParams())¶
Trains SVM.
The method trains the SVM model. It follows the conventions of the generic train
“method” with the following limitations: only the CV_ROW_SAMPLE data layout is
supported, the input variables are all ordered, the output variables can be either categorical
(_params.svm_type=CvSVM::C_SVC or _params.svm_type=CvSVM::NU_SVC), or ordered
(_params.svm_type=CvSVM::EPS_SVR or _params.svm_type=CvSVM::NU_SVR), or not
required at all (_params.svm_type=CvSVM::ONE_CLASS), missing measurements are not
supported.
CvSVM::train_auto¶
train_auto(const CvMat* _train_data, const CvMat* _responses, const CvMat* _var_idx, const CvMat*
_sample_idx, CvSVMParams params, int k_fold = 10, CvParamGrid C_grid = get_default_grid(CvSVM::C),
CvParamGrid gamma_grid = get_default_grid(CvSVM::GAMMA), CvParamGrid p_grid =
get_default_grid(CvSVM::P), CvParamGrid nu_grid = get_default_grid(CvSVM::NU), CvParamGrid coef_grid
= get_default_grid(CvSVM::COEF), CvParamGrid degree_grid = get_default_grid(CvSVM::DEGREE))¶
k_fold – Cross-validation parameter. The training set is divided into k_fold subsets,
Parameter: one subset being used to train the model, the others forming the test set. So, the SVM
algorithm is executed k_fold times.
The method trains the SVM model automatically by choosing the optimal parameters C,
gamma, p, nu, coef0, degree from CvSVMParams. By optimal one means that the cross-
validation estimate of the test set error is minimal. The parameters are iterated by a
logarithmic grid, for example, the parameter gamma takes the values in the set ( ,
, , ... ) where is gamma_grid.min_val,
is gamma_grid.step, and is the maximal index such, that
So step must always be greater than 1.
If there is no need in optimization in some parameter, the according grid step should be set
to any value less or equal to 1. For example, to avoid optimization in gamma one should set
gamma_grid.step = 0, gamma_grid.min_val, gamma_grid.max_val being arbitrary
numbers. In this case, the value params.gamma will be taken for gamma.
And, finally, if the optimization in some parameter is required, but there is no idea of the
corresponding grid, one may call the function CvSVM::get_default_grid. In order to
generate a grid, say, for gamma, call CvSVM::get_default_grid(CvSVM::GAMMA).
CvSVM::get_default_grid¶
CvParamGrid CvSVM::get_default_grid(int param_id)¶
param_id –
• CvSVM::C -
Parameter:
• CvSVM::GAMMA -
• CvSVM::P -
• CvSVM::NU -
• CvSVM::COEF -
• CvSVM::DEGREE -
The grid will be generated for the parameter with this ID.
The function generates a grid for the specified parameter of the SVM algorithm. The grid may be passed to
the function CvSVM::train_auto.
CvSVM::get_params¶
CvSVMParams CvSVM::get_params() const¶
Returns the current SVM parameters.
This function may be used to get the optimal parameters that were obtained while
automatically training CvSVM::train_auto.
CvSVM::get_support_vector*¶
int CvSVM::get_support_vector_count() const¶
Decision Trees¶
The ML classes discussed in this section implement Classification And Regression Tree algorithms,
which are described in bgroup({#paper_Breiman84})bgroup({[Breiman84]}).
The class CvDTree represents a single decision tree that may be used alone, or as a base class in tree
ensembles (see Boosting and Random Trees).
A decision tree is a binary tree (i.e. tree where each non-leaf node has exactly 2 child nodes). It can
be used either for classification, when each tree leaf is marked with some class label (multiple leafs
may have the same label), or for regression, when each tree leaf is also assigned a constant (so the
approximation function is piecewise constant).
Sometimes, certain features of the input vector are missed (for example, in the darkness it is
difficult to determine the object color), and the prediction procedure may get stuck in the certain
node (in the mentioned example if the node is split by color). To avoid such situations, decision
trees use so-called surrogate splits. That is, in addition to the best “primary” split, every tree node
may also be split on one or more other variables with nearly the same results.
Training Decision Trees¶
The tree is built recursively, starting from the root node. All of the training data (feature vectors and
the responses) is used to split the root node. In each node the optimum decision rule (i.e. the best
“primary” split) is found based on some criteria (in ML gini “purity” criteria is used for
classification, and sum of squared errors is used for regression). Then, if necessary, the surrogate
splits are found that resemble the results of the primary split on the training data; all of the data is
divided using the primary and the surrogate splits (just like it is done in the prediction procedure)
between the left and the right child node. Then the procedure recursively splits both left and right
nodes. At each node the recursive procedure may stop (i.e. stop splitting the node further) in one of
the following cases:
• bgroup({depth of the tree branch being constructed has reached the specified maximum value.})
• bgroup({number of training samples in the node is less than the specified threshold, when it is not
statistically representative to split the node further.})
• bgroup({all the samples in the node belong to the same class (or, in the case of regression, the
variation is too small).})
• bgroup({the best split found does not give any noticeable improvement compared to a random
choice.})
When the tree is built, it may be pruned using a cross-validation procedure, if necessary. That is,
some branches of the tree that may lead to the model overfitting are cut off. Normally this
procedure is only applied to standalone decision trees, while tree ensembles usually build small
enough trees and use their own protection schemes against overfitting.
Variable importance¶
Besides the obvious use of decision trees - prediction, the tree can be also used for various data
analysis. One of the key properties of the constructed decision tree algorithms is that it is possible to
compute importance (relative decisive power) of each variable. For example, in a spam filter that
uses a set of words occurred in the message as a feature vector, the variable importance rating can
be used to determine the most “spam-indicating” words and thus help to keep the dictionary size
reasonable.
Importance of each variable is computed over all the splits on this variable in the tree, primary and
surrogate ones. Thus, to compute variable importance correctly, the surrogate splits must be enabled
in the training parameters, even if there is no missing data.
[Breiman84] Breiman, L., Friedman, J. Olshen, R. and Stone, C. (1984), “Classification and
Regression Trees”, Wadsworth.
CvDTreeSplit¶
Decision tree node split.
struct CvDTreeSplit
{
int var_idx;
int inversed;
float quality;
CvDTreeSplit* next;
union
{
int subset[2];
struct
{
float c;
int split_point;
}
ord;
};
};
CvDTreeNode¶
Decision tree node.
struct CvDTreeNode
{
int class_idx;
int Tn;
double value;
CvDTreeNode* parent;
CvDTreeNode* left;
CvDTreeNode* right;
CvDTreeSplit* split;
int sample_count;
int depth;
...
};
Other numerous fields of CvDTreeNode are used internally at the training stage.
CvDTreeParams¶
Decision tree training parameters.
struct CvDTreeParams
{
int max_categories;
int max_depth;
int min_sample_count;
int cv_folds;
bool use_surrogates;
bool use_1se_rule;
bool truncate_pruned_tree;
float regression_accuracy;
const float* priors;
The structure contains all the decision tree training parameters. There is a default constructor that
initializes all the parameters with the default values tuned for standalone classification tree. Any of
the parameters can be overridden then, or the structure may be fully initialized using the advanced
variant of the constructor.
CvDTreeTrainData¶
Decision tree training data and shared data for tree ensembles.
struct CvDTreeTrainData
{
CvDTreeTrainData();
CvDTreeTrainData( const CvMat* _train_data, int _tflag,
const CvMat* _responses, const CvMat* _var_idx=0,
const CvMat* _sample_idx=0, const CvMat* _var_type=0,
const CvMat* _missing_mask=0,
const CvDTreeParams& _params=CvDTreeParams(),
bool _shared=false, bool _add_labels=false );
virtual ~CvDTreeTrainData();
////////////////////////////////////
CvMat* cat_count;
CvMat* cat_ofs;
CvMat* cat_map;
CvMat* counts;
CvMat* buf;
CvMat* direction;
CvMat* split_buf;
CvMat* var_idx;
CvMat* var_type; // i-th element =
// k<0 - ordered
// k>=0 - categorical, see k-th element of cat_* arrays
CvMat* priors;
CvDTreeParams params;
CvMemStorage* tree_storage;
CvMemStorage* temp_storage;
CvDTreeNode* data_root;
CvSet* node_heap;
CvSet* split_heap;
CvSet* cv_heap;
CvSet* nv_heap;
CvRNG rng;
};
This structure is mostly used internally for storing both standalone trees and tree ensembles
efficiently. Basically, it contains 3 types of information:
There are 2 ways of using this structure. In simple cases (e.g. a standalone tree, or the ready-to-use
“black box” tree ensemble from ML, like Random Trees or Boosting) there is no need to care or
even to know about the structure - just construct the needed statistical model, train it and use it. The
CvDTreeTrainData structure will be constructed and used internally. However, for custom tree
algorithms, or another sophisticated cases, the structure may be constructed and used explicitly. The
scheme is the following:
• The structure is initialized using the default constructor, followed by set_data (or it is built using
the full form of constructor). The parameter _shared must be set to true.
• One or more trees are trained using this data, see the special form of the method
CvDTree::train.
• Finally, the structure can be released only after all the trees using it are released.
CvDTree¶
Decision tree.
// special read & write methods for trees in the tree ensembles
virtual void read( CvFileStorage* fs, CvFileNode* node,
CvDTreeTrainData* data );
virtual void write( CvFileStorage* fs );
protected:
CvDTreeNode* root;
int pruned_tree_idx;
CvMat* var_importance;
CvDTreeTrainData* data;
};
CvDTree::train¶
bool CvDTree::train(const CvMat* _train_data, int _tflag, const CvMat* _responses, const CvMat*
_var_idx=0, const CvMat* _sample_idx=0, const CvMat* _var_type=0, const CvMat* _missing_mask=0,
CvDTreeParams params=CvDTreeParams())¶
The first method follows the generic CvStatModel::train conventions, it is the most
complete form. Both data layouts (_tflag=CV_ROW_SAMPLE and _tflag=CV_COL_SAMPLE)
are supported, as well as sample and variable subsets, missing measurements, arbitrary
combinations of input and output variable types etc. The last parameter contains all of the
necessary training parameters, see the CvDTreeParams description.
The second method train is mostly used for building tree ensembles. It takes the pre-
constructed CvDTreeTrainData instance and the optional subset of training set. The indices
in _subsample_idx are counted relatively to the _sample_idx, passed to
CvDTreeTrainData constructor. For example, if _sample_idx=[1, 5, 7, 100], then
_subsample_idx=[0,3] means that the samples [1, 100] of the original training set are
used.
CvDTree::predict¶
CvDTreeNode* CvDTree::predict(const CvMat* _sample, const CvMat* _missing_data_mask=0, bool
raw_mode=false) const¶
Returns the leaf node of the decision tree corresponding to the input vector.
The method takes the feature vector and the optional missing measurement mask on input,
traverses the decision tree and returns the reached leaf node on output. The prediction result,
either the class label or the estimated function value, may be retrieved as the value field of
the CvDTreeNode structure, for example: dtree-:math:`$>$`predict(sample,mask)-
:math:`$>$`value.
The last parameter is normally set to false, implying a regular input. If it is true, the
method assumes that all the values of the discrete input variables have been already
normalized to to ranges. (as the decision tree uses such
normalized representation internally). It is useful for faster prediction with tree ensembles.
For ordered input variables the flag is not used.
Example: Building A Tree for Classifying Mushrooms. See the mushroom.cpp sample that
demonstrates how to build and use the decision tree.
Boosting¶
A common machine learning task is supervised learning. In supervised learning, the goal is to learn
the functional relationship between the input and the output . Predicting the
qualitative output is called classification, while predicting the quantitative output is called
regression.
Boosting is a powerful learning concept, which provide a solution to the supervised classification
learning task. It combines the performance of many “weak” classifiers to produce a powerful
‘committee’ HTF01. A weak classifier is only required to be better than chance, and thus can be
very simple and computationally inexpensive. Many of them smartly combined, however, results in
a strong classifier, which often outperforms most ‘monolithic’ strong classifiers such as SVMs and
Neural Networks.
Decision trees are the most popular weak classifiers used in boosting schemes. Often the simplest
decision trees with only a single split node per tree (called stumps) are sufficient.
Different variants of boosting are known such as Discrete Adaboost, Real AdaBoost, LogitBoost,
and Gentle AdaBoost FHT98. All of them are very similar in their overall structure. Therefore, we
will look only at the standard two-class Discrete AdaBoost algorithm as shown in the box below.
Each sample is initially assigned the same weight (step 2). Next a weak classifier is trained on
the weighted training data (step 3a). Its weighted training error and scaling factor is computed
(step 3b). The weights are increased for training samples, which have been misclassified (step 3c).
All weights are then normalized, and the process of finding the next weak classifier continues for
another -1 times. The final classifier is the sign of the weighted sum over the individual
weak classifiers (step 4).
Two-class Discrete AdaBoost Algorithm: Training (steps 1 to 3) and Evaluation (step 4) NOTE: As
well as the classical boosting methods, the current implementation supports 2-class classifiers only.
For M:math:$>$`2 classes there is the AdaBoost.MH algorithm, described in :ref:`FHT98, that
reduces the problem to the 2-class problem, yet with a much larger training set.
In order to reduce computation time for boosted models without substantially losing accuracy, the
influence trimming technique may be employed. As the training algorithm proceeds and the number
of trees in the ensemble is increased, a larger number of the training samples are classified correctly
and with increasing confidence, thereby those samples receive smaller weights on the subsequent
iterations. Examples with very low relative weight have small impact on training of the weak
classifier. Thus such examples may be excluded during the weak classifier training without having
much effect on the induced classifier. This process is controlled with the weight_trim_rate
parameter. Only examples with the summary fraction weight_trim_rate of the total weight mass are
used in the weak classifier training. Note that the weights for all training examples are recomputed
at each training iteration. Examples deleted at a particular iteration may be used again for learning
some of the weak classifiers further FHT98.
[HTF01] Hastie, T., Tibshirani, R., Friedman, J. H. The Elements of Statistical Learning: Data
Mining, Inference, and Prediction. Springer Series in Statistics. 2001.
[FHT98] Friedman, J. H., Hastie, T. and Tibshirani, R. Additive Logistic Regression: a Statistical
View of Boosting. Technical Report, Dept. of Statistics, Stanford University, 1998.
CvBoostParams¶
Boosting training parameters.
CvBoostParams();
CvBoostParams( int boost_type, int weak_count, double weight_trim_rate,
int max_depth, bool use_surrogates, const float* priors );
};
The structure is derived from CvDTreeParams, but not all of the decision tree parameters are
supported. In particular, cross-validation is not supported.
CvBoostTree¶
Weak tree classifier.
protected:
...
CvBoost* ensemble;
};
The weak classifier, a component of the boosted tree classifier CvBoost, is a derivative of CvDTree.
Normally, there is no need to use the weak classifiers directly, however they can be accessed as
elements of the sequence CvBoost::weak, retrieved by CvBoost::get_weak_predictors.
Note, that in the case of LogitBoost and Gentle AdaBoost each weak predictor is a regression tree,
rather than a classification tree. Even in the case of Discrete AdaBoost and Real AdaBoost the
CvBoostTree::predict return value (CvDTreeNode::value) is not the output class label; a
negative value “votes” for class 0, a positive - for class 1. And the votes are weighted. The weight
of each individual tree may be increased or decreased using the method CvBoostTree::scale.
CvBoost¶
Boosted tree classifier.
// Splitting criteria
enum { DEFAULT=0, GINI=1, MISCLASS=3, SQERR=4 };
CvBoost();
virtual ~CvBoost();
CvSeq* get_weak_predictors();
const CvBoostParams& get_params() const;
...
protected:
virtual bool set_params( const CvBoostParams& _params );
virtual void update_weights( CvBoostTree* tree );
virtual void trim_weights();
virtual void write_params( CvFileStorage* fs );
virtual void read_params( CvFileStorage* fs, CvFileNode* node );
CvDTreeTrainData* data;
CvBoostParams params;
CvSeq* weak;
...
};
CvBoost::train¶
bool CvBoost::train(const CvMat* _train_data, int _tflag, const CvMat* _responses, const CvMat*
_var_idx=0, const CvMat* _sample_idx=0, const CvMat* _var_type=0, const CvMat* _missing_mask=0,
CvBoostParams params=CvBoostParams(), bool update=false)¶
The train method follows the common template; the last parameter update specifies whether
the classifier needs to be updated (i.e. the new weak tree classifiers added to the existing
ensemble), or the classifier needs to be rebuilt from scratch. The responses must be
categorical, i.e. boosted trees can not be built for regression, and there should be 2 classes.
CvBoost::predict¶
float CvBoost::predict(const CvMat* sample, const CvMat* missing=0, CvMat* weak_responses=0,
CvSlice slice=CV_WHOLE_SEQ, bool raw_mode=false) const¶
The method CvBoost::predict runs the sample through the trees in the ensemble and
returns the output class label based on the weighted voting.
CvBoost::prune¶
void CvBoost::prune(CvSlice slice)¶
The method removes the specified weak classifiers from the sequence. Note that this method
should not be confused with the pruning of individual decision trees, which is currently not
supported.
CvBoost::get_weak_predictors¶
CvSeq* CvBoost::get_weak_predictors()¶
The method returns the sequence of weak classifiers. Each element of the sequence is a
pointer to a CvBoostTree class (or, probably, to some of its derivatives).
Random Trees¶
Random trees have been introduced by Leo Breiman and Adele Cutler:
http://www.stat.berkeley.edu/users/breiman/RandomForests/. The algorithm can deal with both
classification and regression problems. Random trees is a collection (ensemble) of tree predictors
that is called forest further in this section (the term has been also introduced by L. Breiman). The
classification works as follows: the random trees classifier takes the input feature vector, classifies
it with every tree in the forest, and outputs the class label that recieved the majority of “votes”. In
the case of regression the classifier response is the average of the responses over all the trees in the
forest.
All the trees are trained with the same parameters, but on the different training sets, which are
generated from the original training set using the bootstrap procedure: for each training set we
randomly select the same number of vectors as in the original set (=N). The vectors are chosen with
replacement. That is, some vectors will occur more than once and some will be absent. At each
node of each tree trained not all the variables are used to find the best split, rather than a random
subset of them. With each node a new subset is generated, however its size is fixed for all the nodes
and all the trees. It is a training parameter, set to by default. None of
the trees that are built are pruned.
In random trees there is no need for any accuracy estimation procedures, such as cross-validation or
bootstrap, or a separate test set to get an estimate of the training error. The error is estimated
internally during the training. When the training set for the current tree is drawn by sampling with
replacement, some vectors are left out (so-called oob (out-of-bag) data). The size of oob data is
about N/3. The classification error is estimated by using this oob-data as following:
• Get a prediction for each vector, which is oob relatively to the i-th tree, using the very i-th tree.
• After all the trees have been trained, for each vector that has ever been oob, find the class-
“winner” for it (i.e. the class that has got the majority of votes in the trees, where the vector was
oob) and compare it to the ground-truth response.
• Then the classification error estimate is computed as ratio of number of misclassified oob vectors
to all the vectors in the original data. In the case of regression the oob-error is computed as the
squared error for oob vectors difference divided by the total number of vectors.
References:
CvRTParams¶
Training Parameters of Random Trees.
The set of training parameters for the forest is the superset of the training parameters for a single
tree. However, Random trees do not need all the functionality/features of decision trees, most
noticeably, the trees are not pruned, so the cross-validation parameters are not used.
CvRTrees¶
Random Trees.
CvMat* get_active_var_mask();
CvRNG* get_rng();
protected:
CvRTrees::train¶
bool CvRTrees::train(const CvMat* train_data, int tflag, const CvMat* responses, const CvMat*
comp_idx=0, const CvMat* sample_idx=0, const CvMat* var_type=0, const CvMat* missing_mask=0,
CvRTParams params=CvRTParams())¶
The method CvRTrees::train is very similar to the first form of CvDTree::train`() and
follows the generic method :ctype:`CvStatModel::train conventions. All of the
specific to the algorithm training parameters are passed as a CvRTParams instance. The
estimate of the training error (oob-error) is stored in the protected class member
oob_error.
CvRTrees::predict¶
double CvRTrees::predict(const CvMat* sample, const CvMat* missing=0) const¶
The input parameters of the prediction method are the same as in CvDTree::predict, but
the return value type is different. This method returns the cumulative result from all the trees
in the forest (the class that receives the majority of voices, or the mean of the regression
function estimates).
CvRTrees::get_var_importance¶
const CvMat* CvRTrees::get_var_importance() const¶
The method returns the variable importance vector, computed at the training stage when
:ref:`CvRTParams`::calc_var_importance is set. If the training flag is not set, then the
NULL pointer is returned. This is unlike decision trees, where variable importance can be
computed anytime after the training.
CvRTrees::get_proximity¶
float CvRTrees::get_proximity(const CvMat* sample_1, const CvMat* sample_2) const¶
The method returns proximity measure between any two samples (the ratio of the those trees
in the ensemble, in which the samples fall into the same leaf node, to the total number of the
trees).
#include <float.h>
#include <stdio.h>
#include <ctype.h>
#include "ml.h"
resp_col = 0;
cvGetCol( &train_data, &response, resp_col);
cvReleaseMat(&missed);
cvReleaseMat(&sample_idx);
cvReleaseMat(&comp_idx);
cvReleaseMat(&type_mask);
cvReleaseMat(&data);
cvReleaseStatModel(&cls);
cvReleaseFileStorage(&storage);
return 0;
}
Expectation-Maximization¶
The EM (Expectation-Maximization) algorithm estimates the parameters of the multivariate
probability density function in the form of a Gaussian mixture distribution with a specified number
of mixtures.
Consider the set of the feature vectors : N vectors from a d-dimensional Euclidean
space drawn from a Gaussian mixture:
where is the number of mixtures, is the normal distribution density with the mean and
covariance matrix , is the weight of the k-th mixture. Given the number of mixtures and
the samples , the algorithm finds the maximum-likelihood estimates (MLE) of the all
the mixture parameters, i.e. , and :
EM algorithm is an iterative procedure. Each iteration of it includes two steps. At the first step
(Expectation-step, or E-step), we find a probability (denoted in the formula below) of
sample i to belong to mixture k using the currently available mixture parameter estimates:
At the second step (Maximization-step, or M-step) the mixture parameter estimates are refined
using the computed probabilities:
Alternatively, the algorithm may start with the M-step when the initial values for can be
provided. Another alternative when are unknown, is to use a simpler clustering algorithm to
pre-cluster the input samples and thus obtain initial . Often (and in ML) the KMeans2 algorithm
is used for that purpose.
One of the main that EM algorithm should deal with is the large number of parameters to estimate.
The majority of the parameters sits in covariance matrices, which are elements each (where
is the feature space dimensionality). However, in many practical problems the covariance
matrices are close to diagonal, or even to , where is identity matrix and is mixture-
dependent “scale” parameter. So a robust computation scheme could be to start with the harder
constraints on the covariance matrices and then use the estimated parameters as an input for a less
constrained optimization problem (often a diagonal covariance matrix is already a good enough
approximation).
References:
• Bilmes98 J. A. Bilmes. A Gentle Tutorial of the EM Algorithm and its Application to Parameter
Estimation for Gaussian Mixture and Hidden Markov Models. Technical Report TR-97-021,
International Computer Science Institute and Computer Science Division, University of California at
Berkeley, April 1998.
CvEMParams¶
Parameters of the EM algorithm.
struct CvEMParams
{
CvEMParams() : nclusters(10), cov_mat_type(CvEM::COV_MAT_DIAGONAL),
start_step(CvEM::START_AUTO_STEP), probs(0), weights(0), means(0),
covs(0)
{
term_crit=cvTermCriteria( CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
100, FLT_EPSILON );
}
int nclusters;
int cov_mat_type;
int start_step;
const CvMat* probs;
const CvMat* weights;
const CvMat* means;
const CvMat** covs;
CvTermCriteria term_crit;
};
The structure has 2 constructors, the default one represents a rough rule-of-thumb, with another one
it is possible to override a variety of parameters, from a single number of mixtures (the only
essential problem-dependent parameter), to the initial values for the mixture parameters.
CvEM¶
EM model.
CvEM();
CvEM( const CvMat* samples, const CvMat* sample_idx=0,
CvEMParams params=CvEMParams(), CvMat* labels=0 );
virtual ~CvEM();
protected:
CvMat* means;
CvMat** covs;
CvMat* weights;
CvMat* probs;
CvMat* log_weight_div_det;
CvMat* inv_eigen_values;
CvMat** cov_rotate_mats;
};
CvEM::train¶
void CvEM::train(const CvMat* samples, const CvMat* sample_idx=0, CvEMParams
params=CvEMParams(), CvMat* labels=0)¶
Unlike many of the ML models, EM is an unsupervised learning algorithm and it does not
take responses (class labels or the function values) on input. Instead, it computes the MLE of
the Gaussian mixture parameters from the input sample set, stores all the parameters inside
the structure: in probs, in means in covs[k], in weights and optionally
computes the output “class label” for each sample:
(i.e. indices of the most-probable mixture for each
sample).
The trained model can be used further for prediction, just like any other classifier. The
model trained is similar to the Bayes classifier.
#include "ml.h"
#include "highgui.h"
#if 0
// the piece of code shows how to repeatedly optimize the model
// with less-constrained parameters
//(COV_MAT_DIAGONAL instead of COV_MAT_SPHERICAL)
// when the output of the first stage is used as input for the second.
CvEM em_model2;
params.cov_mat_type = CvEM::COV_MAT_DIAGONAL;
params.start_step = CvEM::START_E_STEP;
params.means = em_model.get_means();
params.covs = (const CvMat**)em_model.get_covs();
params.weights = em_model.get_weights();
cvReleaseMat( &samples );
cvReleaseMat( &labels );
return 0;
}
Neural Networks¶
ML implements feed-forward artificial neural networks, more particularly, multi-layer perceptrons
(MLP), the most commonly used type of neural networks. MLP consists of the input layer, output
layer and one or more hidden layers. Each layer of MLP includes one or more neurons that are
directionally linked with the neurons from the previous and the next layer. Here is an example of a
3-layer perceptron with 3 inputs, 2 outputs and the hidden layer including 5 neurons:
All the neurons in MLP are similar. Each of them has several input links (i.e. it takes the output
values from several neurons in the previous layer on input) and several output links (i.e. it passes
the response to several neurons in the next layer). The values retrieved from the previous layer are
summed with certain weights, individual for each neuron, plus the bias term, and the sum is
transformed using the activation function that may be also different for different neurons. Here is
the picture:
In other words, given the outputs of the layer , the outputs of the layer are computed
as:
Different activation functions may be used, ML implements 3 standard ones:
In ML all the neurons have the same activation functions, with the same free parameters ( ) that
are specified by user and are not altered by the training algorithms.
So the whole trained network works as follows: It takes the feature vector on input, the vector size
is equal to the size of the input layer, when the values are passed as input to the first hidden layer,
the outputs of the hidden layer are computed using the weights and the activation functions and
passed further downstream, until we compute the output layer.
So, in order to compute the network one needs to know all the weights . The weights are
computed by the training algorithm. The algorithm takes a training set: multiple input vectors with
the corresponding output vectors, and iteratively adjusts the weights to try to make the network give
the desired response on the provided input vectors.
The larger the network size (the number of hidden layers and their sizes), the more is the potential
network flexibility, and the error on the training set could be made arbitrarily small. But at the same
time the learned network will also “learn” the noise present in the training set, so the error on the
test set usually starts increasing after the network size reaches some limit. Besides, the larger
networks are train much longer than the smaller ones, so it is reasonable to preprocess the data
(using CalcPCA or similar technique) and train a smaller network on only the essential features.
Another feature of the MLP’s is their inability to handle categorical data as is, however there is a
workaround. If a certain feature in the input or output (i.e. in the case of n-class classifier for
) layer is categorical and can take different values, it makes sense to represent it as
binary tuple of M elements, where i-th element is 1 if and only if the feature is equal to the i-th
value out of M possible. It will increase the size of the input/output layer, but will speedup the
training algorithm convergence and at the same time enable “fuzzy” values of such variables, i.e. a
tuple of probabilities instead of a fixed value.
ML implements 2 algorithms for training MLP’s. The first is the classical random sequential back-
propagation algorithm and the second (default one) is batch RPROP algorithm.
References:
13. Riedmiller and H. Braun, “A Direct Adaptive Method for Faster Backpropagation Learning:
The RPROP Algorithm”, Proc. ICNN, San Francisco (1993).
CvANN_MLP_TrainParams¶
Parameters of the MLP training algorithm.
struct CvANN_MLP_TrainParams
{
CvANN_MLP_TrainParams();
CvANN_MLP_TrainParams( CvTermCriteria term_crit, int train_method,
double param1, double param2=0 );
~CvANN_MLP_TrainParams();
CvTermCriteria term_crit;
int train_method;
// backpropagation parameters
double bp_dw_scale, bp_moment_scale;
// rprop parameters
double rp_dw0, rp_dw_plus, rp_dw_minus, rp_dw_min, rp_dw_max;
};
The structure has default constructor that initializes parameters for RPROP algorithm. There is also
more advanced constructor to customize the parameters and/or choose backpropagation algorithm.
Finally, the individual parameters can be adjusted after the structure is created.
CvANN_MLP¶
MLP model.
class CvANN_MLP : public CvStatModel
{
public:
CvANN_MLP();
CvANN_MLP( const CvMat* _layer_sizes,
int _activ_func=SIGMOID_SYM,
double _f_param1=0, double _f_param2=0 );
virtual ~CvANN_MLP();
protected:
// RPROP algorithm
virtual int train_rprop( CvVectors _ivecs, CvVectors _ovecs,
const double* _sw );
CvMat* layer_sizes;
CvMat* wbuf;
CvMat* sample_weights;
double** weights;
double f_param1, f_param2;
double min_val, max_val, min_val1, max_val1;
int activ_func;
int max_count, max_buf_sz;
CvANN_MLP_TrainParams params;
CvRNG rng;
};
Unlike many other models in ML that are constructed and trained at once, in the MLP model these
steps are separated. First, a network with the specified topology is created using the non-default
constructor or the method create. All the weights are set to zeros. Then the network is trained
using the set of input and output vectors. The training procedure can be repeated more than once,
i.e. the weights can be adjusted based on the new training data.
CvANN_MLP::create¶
void CvANN_MLP::create(const CvMat* _layer_sizes, int _activ_func=SIGMOID_SYM, double
_f_param1=0, double _f_param2=0)¶
The method creates a MLP network with the specified topology and assigns the same
activation function to all the neurons.
CvANN_MLP::train¶
int CvANN_MLP::train(const CvMat* _inputs, const CvMat* _outputs, const CvMat* _sample_weights,
const CvMat* _sample_idx=0, CvANN_MLP_TrainParams _params = CvANN_MLP_TrainParams(), int
flags=0)¶
Trains/updates MLP.
This method applies the specified training algorithm to compute/adjust the network weights.
It returns the number of done iterations.