CXCORE Reference Manual



Basic Structures


CvPoint

2D point with integer coordinates

    typedef struct CvPoint
    {
        int x; /* x-coordinate, usually zero-based */
        int y; /* y-coordinate, usually zero-based */
    }
    CvPoint;

    /* the constructor function */
    inline CvPoint cvPoint( int x, int y );

    /* conversion from CvPoint2D32f */
    inline CvPoint cvPointFrom32f( CvPoint2D32f point );

CvPoint2D32f

2D point with floating-point coordinates

    typedef struct CvPoint2D32f
    {
        float x; /* x-coordinate, usually zero-based */
        float y; /* y-coordinate, usually zero-based */
    }
    CvPoint2D32f;

    /* the constructor function */
    inline CvPoint2D32f cvPoint2D32f( double x, double y );

    /* conversion from CvPoint */
    inline CvPoint2D32f cvPointTo32f( CvPoint point );

CvPoint3D32f

3D point with floating-point coordinates

    typedef struct CvPoint3D32f
    {
        float x; /* x-coordinate, usually zero-based */
        float y; /* y-coordinate, usually zero-based */
        float z; /* z-coordinate, usually zero-based */
    }
    CvPoint3D32f;

    /* the constructor function */
    inline CvPoint3D32f cvPoint3D32f( double x, double y, double z );

CvPoint2D64f

2D point with double precision floating-point coordinates

    typedef struct CvPoint2D64f
    {
        double x; /* x-coordinate, usually zero-based */
        double y; /* y-coordinate, usually zero-based */
    }
    CvPoint2D64f;

    /* the constructor function */
    inline CvPoint2D64f cvPoint2D64f( double x, double y );

    /* conversion from CvPoint */
    inline CvPoint2D64f cvPointTo64f( CvPoint point );

CvPoint3D64f

3D point with double precision floating-point coordinates

    typedef struct CvPoint3D64f
    {
        double x; /* x-coordinate, usually zero-based */
        double y; /* y-coordinate, usually zero-based */
        double z; /* z-coordinate, usually zero-based */
    }
    CvPoint3D64f;

    /* the constructor function */
    inline CvPoint3D64f cvPoint3D64f( double x, double y, double z );

CvSize

pixel-accurate size of a rectangle

    typedef struct CvSize
    {
        int width; /* width of the rectangle */
        int height; /* height of the rectangle */
    }
    CvSize;

    /* the constructor function */
    inline CvSize cvSize( int width, int height );

CvSize2D32f

sub-pixel accurate size of a rectangle

    typedef struct CvSize2D32f
    {
        float width; /* width of the box */
        float height; /* height of the box */
    }
    CvSize2D32f;

    /* the constructor function */
    inline CvSize2D32f cvSize2D32f( double width, double height );

CvRect

offset and size of a rectangle

    typedef struct CvRect
    {
        int x; /* x-coordinate of the left-most rectangle corner[s] */
        int y; /* y-coordinate of the top-most or bottom-most
                  rectangle corner[s] */
        int width; /* width of the rectangle */
        int height; /* height of the rectangle */
    }
    CvRect;

    /* the constructor function */
    inline CvRect cvRect( int x, int y, int width, int height );

CvScalar

A container for 1-,2-,3- or 4-tuples of numbers

    typedef struct CvScalar
    {
        double val[4];
    }
    CvScalar;

    /* the constructor function: initializes val[0] with val0, val[1] with val1 etc. */
    inline CvScalar cvScalar( double val0, double val1=0,
                              double val2=0, double val3=0 );
    /* the constructor function: initializes val[0]...val[3] with val0123 */
    inline CvScalar cvScalarAll( double val0123 );

    /* the constructor function: initializes val[0] with val0, val[1]...val[3] with zeros */
    inline CvScalar cvRealScalar( double val0 );

CvTermCriteria

Termination criteria for iterative algorithms

#define CV_TERMCRIT_ITER    1
#define CV_TERMCRIT_NUMBER  CV_TERMCRIT_ITER
#define CV_TERMCRIT_EPS     2

typedef struct CvTermCriteria
{
    int    type;  /* a combination of CV_TERMCRIT_ITER and CV_TERMCRIT_EPS */
    int    max_iter; /* maximum number of iterations */
    double epsilon; /* accuracy to achieve */
}
CvTermCriteria;

/* the constructor function */
inline  CvTermCriteria  cvTermCriteria( int type, int max_iter, double epsilon );

/* check termination criteria and transform it so that type=CV_TERMCRIT_ITER+CV_TERMCRIT_EPS,
   and both max_iter and epsilon are valid */
CvTermCriteria cvCheckTermCriteria( CvTermCriteria criteria,
                                    double default_eps,
                                    int default_max_iters );

CvMat

Multi-channel matrix

    typedef struct CvMat
    {
        int type; /* CvMat signature (CV_MAT_MAGIC_VAL), element type and flags */
        int step; /* full row length in bytes */

        int* refcount; /* underlying data reference counter */

        union
        {
            uchar* ptr;
            short* s;
            int* i;
            float* fl;
            double* db;
        } data; /* data pointers */

    #ifdef __cplusplus
        union
        {
            int rows;
            int height;
        };

        union
        {
            int cols;
            int width;
        };
    #else
        int rows; /* number of rows */
        int cols; /* number of columns */
    #endif

    } CvMat;

CvMatND

Multi-dimensional dense multi-channel array

    typedef struct CvMatND
    {
        int type; /* CvMatND signature (CV_MATND_MAGIC_VAL), element type and flags */
        int dims; /* number of array dimensions */

        int* refcount; /* underlying data reference counter */

        union
        {
            uchar* ptr;
            short* s;
            int* i;
            float* fl;
            double* db;
        } data; /* data pointers */

        /* pairs (number of elements, distance between elements in bytes) for
           every dimension */
        struct
        {
            int size;
            int step;
        }
        dim[CV_MAX_DIM];

    } CvMatND;

CvSparseMat

Multi-dimensional sparse multi-channel array

    typedef struct CvSparseMat
    {
        int type; /* CvSparseMat signature (CV_SPARSE_MAT_MAGIC_VAL), element type and flags */
        int dims; /* number of dimensions */
        int* refcount; /* reference counter - not used */
        struct CvSet* heap; /* a pool of hashtable nodes */
        void** hashtable; /* hashtable: each entry has a list of nodes
                             having the same "hashvalue modulo hashsize" */
        int hashsize; /* size of hashtable */
        int total; /* total number of sparse array nodes */
        int valoffset; /* value offset in bytes for the array nodes */
        int idxoffset; /* index offset in bytes for the array nodes */
        int size[CV_MAX_DIM]; /* arr of dimension sizes */

    } CvSparseMat;

IplImage

IPL image header

    typedef struct _IplImage
    {
        int  nSize;         /* sizeof(IplImage) */
        int  ID;            /* version (=0)*/
        int  nChannels;     /* Most of OpenCV functions support 1,2,3 or 4 channels */
        int  alphaChannel;  /* ignored by OpenCV */
        int  depth;         /* pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16U,
                               IPL_DEPTH_16S, IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported */
        char colorModel[4]; /* ignored by OpenCV */
        char channelSeq[4]; /* ditto */
        int  dataOrder;     /* 0 - interleaved color channels, 1 - separate color channels.
                               cvCreateImage can only create interleaved images */
        int  origin;        /* 0 - top-left origin,
                               1 - bottom-left origin (Windows bitmaps style) */
        int  align;         /* Alignment of image rows (4 or 8).
                               OpenCV ignores it and uses widthStep instead */
        int  width;         /* image width in pixels */
        int  height;        /* image height in pixels */
        struct _IplROI *roi;/* image ROI. when it is not NULL, this specifies image region to process */
        struct _IplImage *maskROI; /* must be NULL in OpenCV */
        void  *imageId;     /* ditto */
        struct _IplTileInfo *tileInfo; /* ditto */
        int  imageSize;     /* image data size in bytes
                               (=image->height*image->widthStep
                               in case of interleaved data)*/
        char *imageData;  /* pointer to aligned image data */
        int  widthStep;   /* size of aligned image row in bytes */
        int  BorderMode[4]; /* border completion mode, ignored by OpenCV */
        int  BorderConst[4]; /* ditto */
        char *imageDataOrigin; /* pointer to a very origin of image data
                                  (not necessarily aligned) -
                                  it is needed for correct image deallocation */
    }
    IplImage;

The structure IplImage came from Intel Image Processing Library where the format is native. OpenCV supports only a subset of possible IplImage formats:

Besides the above restrictions, OpenCV handles ROI differently. It requires that the sizes or ROI sizes of all source and destination images match exactly (according to the operation, e.g. for cvPyrDown destination width(height) must be equal to source width(height) divided by 2 ±1), whereas IPL processes the intersection area - that is, the sizes or ROI sizes of all images may vary independently.


CvArr

Arbitrary array

    typedef void CvArr;

The metatype CvArr* is used only as a function parameter to specify that the function accepts arrays of more than a single type, for example IplImage*, CvMat* or even CvSeq*. The particular array type is determined at runtime by analyzing the first 4 bytes of the header.


Operations on Arrays


Initialization


CreateImage

Creates header and allocates data

IplImage* cvCreateImage( CvSize size, int depth, int channels );

size
Image width and height.
depth
Bit depth of image elements. Can be one of:
IPL_DEPTH_8U - unsigned 8-bit integers
IPL_DEPTH_8S - signed 8-bit integers
IPL_DEPTH_16U - unsigned 16-bit integers
IPL_DEPTH_16S - signed 16-bit integers
IPL_DEPTH_32S - signed 32-bit integers
IPL_DEPTH_32F - single precision floating-point numbers
IPL_DEPTH_64F - double precision floating-point numbers
channels
Number of channels per element(pixel). Can be 1, 2, 3 or 4. The channels are interleaved, for example the usual data layout of a color image is:
b0 g0 r0 b1 g1 r1 ...
Although in general IPL image format can store non-interleaved images as well and some of OpenCV can process it, this function can create interleaved images only.

The function cvCreateImage creates the header and allocates data. This call is a shortened form of

    header = cvCreateImageHeader(size,depth,channels);
    cvCreateData(header);


CreateImageHeader

Allocates, initializes, and returns structure IplImage

IplImage* cvCreateImageHeader( CvSize size, int depth, int channels );

size
Image width and height.
depth
Image depth (see CreateImage).
channels
Number of channels (see CreateImage).

The function cvCreateImageHeader allocates, initializes, and returns the structure IplImage. This call is an analogue of

  iplCreateImageHeader( channels, 0, depth,
                        channels == 1 ? "GRAY" : "RGB",
                        channels == 1 ? "GRAY" : channels == 3 ? "BGR" :
                        channels == 4 ? "BGRA" : "",
                        IPL_DATA_ORDER_PIXEL, IPL_ORIGIN_TL, 4,
                        size.width, size.height,
                        0,0,0,0);
though it does not use IPL functions by default (see also CV_TURN_ON_IPL_COMPATIBILITY macro)


ReleaseImageHeader

Releases header

void cvReleaseImageHeader( IplImage** image );

image
Double pointer to the deallocated header.

The function cvReleaseImageHeader releases the header. This call is an analogue of

    if( image )
    {
        iplDeallocate( *image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI );
        *image = 0;
    }
though it does not use IPL functions by default (see also CV_TURN_ON_IPL_COMPATIBILITY)


ReleaseImage

Releases header and image data

void cvReleaseImage( IplImage** image );

image
Double pointer to the header of the deallocated image.

The function cvReleaseImage releases the header and the image data. This call is a shortened form of

    if( *image )
    {
        cvReleaseData( *image );
        cvReleaseImageHeader( image );
    }


InitImageHeader

Initializes allocated by user image header

IplImage* cvInitImageHeader( IplImage* image, CvSize size, int depth,
                             int channels, int origin=0, int align=4 );

image
Image header to initialize.
size
Image width and height.
depth
Image depth (see CreateImage).
channels
Number of channels (see CreateImage).
origin
IPL_ORIGIN_TL or IPL_ORIGIN_BL.
align
Alignment for image rows, typically 4 or 8 bytes.

The function cvInitImageHeader initializes the image header structure, pointer to which is passed by the user, and returns the pointer.


CloneImage

Makes a full copy of image

IplImage* cvCloneImage( const IplImage* image );

image
Original image.

The function cvCloneImage makes a full copy of the image including header, ROI and data


SetImageCOI

Sets channel of interest to given value

void cvSetImageCOI( IplImage* image, int coi );

image
Image header.
coi
Channel of interest.

The function cvSetImageCOI sets the channel of interest to a given value. Value 0 means that all channels are selected, 1 means that the first channel is selected etc. If ROI is NULL and coi != 0, ROI is allocated. Note that most of OpenCV functions do not support COI, so to process separate image/matrix channel one may copy (via cvCopy or cvSplit) the channel to separate image/matrix, process it and copy the result back (via cvCopy or cvCvtPlaneToPix) if need.


GetImageCOI

Returns index of channel of interest

int cvGetImageCOI( const IplImage* image );

image
Image header.

The function cvGetImageCOI returns channel of interest of the image (it returns 0 if all the channels are selected).


SetImageROI

Sets image ROI to given rectangle

void cvSetImageROI( IplImage* image, CvRect rect );

image
Image header.
rect
ROI rectangle.

The function cvSetImageROI sets the image ROI to a given rectangle. If ROI is NULL and the value of the parameter rect is not equal to the whole image, ROI is allocated. Unlike COI, most of OpenCV functions do support ROI and treat it in a way as it would be a separate image (for example, all the pixel coordinates are counted from top-left or bottom-left (depending on the image origin) corner of ROI)


ResetImageROI

Releases image ROI

void cvResetImageROI( IplImage* image );

image
Image header.

The function cvResetImageROI releases image ROI. After that the whole image is considered selected. The similar result can be achieved by

cvSetImageROI( image, cvRect( 0, 0, image->width, image->height ));
cvSetImageCOI( image, 0 );

But the latter variant does not deallocate image->roi.


GetImageROI

Returns image ROI coordinates

CvRect cvGetImageROI( const IplImage* image );

image
Image header.

The function cvGetImageROI returns image ROI coordinates. The rectangle cvRect(0,0,image->width,image->height) is returned if there is no ROI


CreateMat

Creates new matrix

CvMat* cvCreateMat( int rows, int cols, int type );

rows
Number of rows in the matrix.
cols
Number of columns in the matrix.
type
Type of the matrix elements. Usually it is specified in form CV_<bit_depth>(S|U|F)C<number_of_channels>, for example:
CV_8UC1 means an 8-bit unsigned single-channel matrix, CV_32SC2 means a 32-bit signed matrix with two channels.

The function cvCreateMat allocates header for the new matrix and underlying data, and returns a pointer to the created matrix. It is a short form for:

    CvMat* mat = cvCreateMatHeader( rows, cols, type );
    cvCreateData( mat );

Matrices are stored row by row. All the rows are aligned by 4 bytes.


CreateMatHeader

Creates new matrix header

CvMat* cvCreateMatHeader( int rows, int cols, int type );

rows
Number of rows in the matrix.
cols
Number of columns in the matrix.
type
Type of the matrix elements (see cvCreateMat).

The function cvCreateMatHeader allocates new matrix header and returns pointer to it. The matrix data can further be allocated using cvCreateData or set explicitly to user-allocated data via cvSetData.


ReleaseMat

Deallocates matrix

void cvReleaseMat( CvMat** mat );

mat
Double pointer to the matrix.

The function cvReleaseMat decrements the matrix data reference counter and releases matrix header:

    if( *mat )
        cvDecRefData( *mat );
    cvFree( (void**)mat );


InitMatHeader

Initializes matrix header

CvMat* cvInitMatHeader( CvMat* mat, int rows, int cols, int type,
                        void* data=NULL, int step=CV_AUTOSTEP );

mat
Pointer to the matrix header to be initialized.
rows
Number of rows in the matrix.
cols
Number of columns in the matrix.
type
Type of the matrix elements.
data
Optional data pointer assigned to the matrix header.
step
Full row width in bytes of the data assigned. By default, the minimal possible step is used, i.e., no gaps is assumed between subsequent rows of the matrix.

The function cvInitMatHeader initializes already allocated CvMat structure. It can be used to process raw data with OpenCV matrix functions.

For example, the following code computes matrix product of two matrices, stored as ordinary arrays.

Calculating Product of Two Matrices

   double a[] = { 1, 2, 3, 4
                  5, 6, 7, 8,
                  9, 10, 11, 12 };

   double b[] = { 1, 5, 9,
                  2, 6, 10,
                  3, 7, 11,
                  4, 8, 12 };

   double c[9];
   CvMat Ma, Mb, Mc ;

   cvInitMatHeader( &Ma, 3, 4, CV_64FC1, a );
   cvInitMatHeader( &Mb, 4, 3, CV_64FC1, b );
   cvInitMatHeader( &Mc, 3, 3, CV_64FC1, c );

   cvMatMulAdd( &Ma, &Mb, 0, &Mc );
   // c array now contains product of a(3x4) and b(4x3) matrices


Mat

Initializes matrix header (light-weight variant)

CvMat cvMat( int rows, int cols, int type, void* data=NULL );

rows
Number of rows in the matrix.
cols
Number of columns in the matrix.
type
Type of the matrix elements (see CreateMat).
data
Optional data pointer assigned to the matrix header.

The function cvMat is a fast inline substitution for cvInitMatHeader. Namely, it is equivalent to:

     CvMat mat;
     cvInitMatHeader( &mat, rows, cols, type, data, CV_AUTOSTEP );


CloneMat

Creates matrix copy

CvMat* cvCloneMat( const CvMat* mat );

mat
Input matrix.

The function cvCloneMat creates a copy of input matrix and returns the pointer to it.


CreateMatND

Creates multi-dimensional dense array

CvMatND* cvCreateMatND( int dims, const int* sizes, int type );

dims
Number of array dimensions. It must not exceed CV_MAX_DIM (=32 by default, though it may be changed at build time)
sizes
Array of dimension sizes.
type
Type of array elements. The same as for CvMat

The function cvCreateMatND allocates header for multi-dimensional dense array and the underlying data, and returns pointer to the created array. It is a short form for:

    CvMatND* mat = cvCreateMatNDHeader( dims, sizes, type );
    cvCreateData( mat );

Array data is stored row by row. All the rows are aligned by 4 bytes.


CreateMatNDHeader

Creates new matrix header

CvMatND* cvCreateMatNDHeader( int dims, const int* sizes, int type );

dims
Number of array dimensions.
sizes
Array of dimension sizes.
type
Type of array elements. The same as for CvMat

The function cvCreateMatND allocates header for multi-dimensional dense array. The array data can further be allocated using cvCreateData or set explicitly to user-allocated data via cvSetData.


ReleaseMatND

Deallocates multi-dimensional array

void cvReleaseMatND( CvMatND** mat );

mat
Double pointer to the array.

The function cvReleaseMatND decrements the array data reference counter and releases the array header:

    if( *mat )
        cvDecRefData( *mat );
    cvFree( (void**)mat );


InitMatNDHeader

Initializes multi-dimensional array header

CvMatND* cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, int type, void* data=NULL );

mat
Pointer to the array header to be initialized.
dims
Number of array dimensions.
sizes
Array of dimension sizes.
type
Type of array elements. The same as for CvMat
data
Optional data pointer assigned to the matrix header.

The function cvInitMatNDHeader initializes CvMatND structure allocated by the user.


CloneMatND

Creates full copy of multi-dimensional array

CvMatND* cvCloneMatND( const CvMatND* mat );

mat
Input array.

The function cvCloneMatND creates a copy of input array and returns pointer to it.


DecRefData

Decrements array data reference counter

void cvDecRefData( CvArr* arr );

arr
array header.

The function cvDecRefData decrements CvMat or CvMatND data reference counter if the reference counter pointer is not NULL and deallocates the data if the counter reaches zero. In the current implementation the reference counter is not NULL only if the data was allocated using cvCreateData function, in other cases such as:
external data was assigned to the header using cvSetData
the matrix header presents a part of a larger matrix or image
the matrix header was converted from image or n-dimensional matrix header

the reference counter is set to NULL and thus it is not decremented. Whenever the data is deallocated or not, the data pointer and reference counter pointers are cleared by the function.


IncRefData

Increments array data reference counter

int cvIncRefData( CvArr* arr );

arr
array header.

The function cvIncRefData increments CvMat or CvMatND data reference counter and returns the new counter value if the reference counter pointer is not NULL, otherwise it returns zero.


CreateData

Allocates array data

void cvCreateData( CvArr* arr );

arr
Array header.

The function cvCreateData allocates image, matrix or multi-dimensional array data. Note that in case of matrix types OpenCV allocation functions are used and in case of IplImage they are used too unless CV_TURN_ON_IPL_COMPATIBILITY was called. In the latter case IPL functions are used to allocate the data


ReleaseData

Releases array data

void cvReleaseData( CvArr* arr );

arr
Array header

The function cvReleaseData releases the array data. In case of CvMat or CvMatND it simply calls cvDecRefData(), that is the function can not deallocate external data. See also the note to cvCreateData.


SetData

Assigns user data to the array header

void cvSetData( CvArr* arr, void* data, int step );

arr
Array header.
data
User data.
step
Full row length in bytes.

The function cvSetData assigns user data to the array header. Header should be initialized before using cvCreate*Header, cvInit*Header or cvMat (in case of matrix) function.


GetRawData

Retrieves low-level information about the array

void cvGetRawData( const CvArr* arr, uchar** data,
                   int* step=NULL, CvSize* roi_size=NULL );

arr
Array header.
data
Output pointer to the whole image origin or ROI origin if ROI is set.
step
Output full row length in bytes.
roi_size
Output ROI size.

The function cvGetRawData fills output variables with low-level information about the array data. All output parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with ROI set, parameters of ROI are returned.

The following example shows how to get access to array elements using this function.

Using GetRawData to calculate absolute value of elements of a single-channel floating-point array.

    float* data;
    int step;

    CvSize size;
    int x, y;

    cvGetRawData( array, (uchar**)&data, &step, &size );
    step /= sizeof(data[0]);

    for( y = 0; y < size.height; y++, data += step )
        for( x = 0; x < size.width; x++ )
            data[x] = (float)fabs(data[x]);


GetMat

Returns matrix header for arbitrary array

CvMat* cvGetMat( const CvArr* arr, CvMat* header, int* coi=NULL, int allowND=0 );

arr
Input array.
header
Pointer to CvMat structure used as a temporary buffer.
coi
Optional output parameter for storing COI.
allowND
If non-zero, the function accepts multi-dimensional dense arrays (CvMatND*) and returns 2D (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or more than 2 dimensions). The array must be continuous.

The function cvGetMat returns matrix header for the input array that can be matrix - CvMat, image - IplImage or multi-dimensional dense array - CvMatND* (latter case is allowed only if allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of IplImage* or CvMatND* it initializes header structure with parameters of the current image ROI and returns pointer to this temporary structure. Because COI is not supported by CvMat, it is returned separately.

The function provides an easy way to handle both types of array - IplImage and CvMat -, using the same code. Reverse transform from CvMat to IplImage can be done using cvGetImage function.

Input array must have underlying data allocated or attached, otherwise the function fails.

If the input array is IplImage with planar data layout and COI set, the function returns pointer to the selected plane and COI = 0. It enables per-plane processing of multi-channel images with planar data layout using OpenCV functions.


GetImage

Returns image header for arbitrary array

IplImage* cvGetImage( const CvArr* arr, IplImage* image_header );

arr
Input array.
image_header
Pointer to IplImage structure used as a temporary buffer.

The function cvGetImage returns image header for the input array that can be matrix - CvMat*, or image - IplImage*. In the case of image the function simply returns the input pointer. In the case of CvMat* it initializes image_header structure with parameters of the input matrix. Note that if we transform IplImage to CvMat and then transform CvMat back to IplImage, we can get different headers if the ROI is set, and thus some IPL functions that calculate image stride from its width and align may fail on the resultant image.


CreateSparseMat

Creates sparse array

CvSparseMat* cvCreateSparseMat( int dims, const int* sizes, int type );

dims
Number of array dimensions. As opposite to the dense matrix, the number of dimensions is practically unlimited (up to 216).
sizes
Array of dimension sizes.
type
Type of array elements. The same as for CvMat

The function cvCreateSparseMat allocates multi-dimensional sparse array. Initially the array contain no elements, that is cvGet*D or cvGetReal*D return zero for every index


ReleaseSparseMat

Deallocates sparse array

void cvReleaseSparseMat( CvSparseMat** mat );

mat
Double pointer to the array.

The function cvReleaseSparseMat releases the sparse array and clears the array pointer upon exit


CloneSparseMat

Creates full copy of sparse array

CvSparseMat* cvCloneSparseMat( const CvSparseMat* mat );

mat
Input array.

The function cvCloneSparseMat creates a copy of the input array and returns pointer to the copy.


Accessing Elements and sub-Arrays


GetSubRect

Returns matrix header corresponding to the rectangular sub-array of input image or matrix

CvMat* cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect );

arr
Input array.
submat
Pointer to the resultant sub-array header.
rect
Zero-based coordinates of the rectangle of interest.

The function cvGetSubRect returns header, corresponding to a specified rectangle of the input array. In other words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is taken into account by the function so the sub-array of ROI is actually extracted.


GetRow, GetRows

Returns array row or row span

CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row );
CvMat* cvGetRows( const CvArr* arr, CvMat* submat, int start_row, int end_row, int delta_row=1 );

arr
Input array.
submat
Pointer to the resulting sub-array header.
row
Zero-based index of the selected row.
start_row
Zero-based index of the starting row (inclusive) of the span.
end_row
Zero-based index of the ending row (exclusive) of the span.
delta_row
Index step in the row span. That is, the function extracts every delta_row-th row from start_row and up to (but not including) end_row.

The functions GetRow and GetRows return the header, corresponding to a specified row/row span of the input array. Note that GetRow is a shortcut for cvGetRows:

cvGetRow( arr, submat, row ) ~ cvGetRows( arr, submat, row, row + 1, 1 );


GetCol, GetCols

Returns array column or column span

CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col );
CvMat* cvGetCols( const CvArr* arr, CvMat* submat, int start_col, int end_col );

arr
Input array.
submat
Pointer to the resulting sub-array header.
col
Zero-based index of the selected column.
start_col
Zero-based index of the starting column (inclusive) of the span.
end_col
Zero-based index of the ending column (exclusive) of the span.

The functions GetCol and GetCols return the header, corresponding to a specified column/column span of the input array. Note that GetCol is a shortcut for cvGetCols:

cvGetCol( arr, submat, col ); // ~ cvGetCols( arr, submat, col, col + 1 );


GetDiag

Returns one of array diagonals

CvMat* cvGetDiag( const CvArr* arr, CvMat* submat, int diag=0 );

arr
Input array.
submat
Pointer to the resulting sub-array header.
diag
Array diagonal. Zero corresponds to the main diagonal, -1 corresponds to the diagonal above the main etc., 1 corresponds to the diagonal below the main etc.

The function cvGetDiag returns the header, corresponding to a specified diagonal of the input array.


GetSize

Returns size of matrix or image ROI

CvSize cvGetSize( const CvArr* arr );

arr
array header.

The function cvGetSize returns number of rows (CvSize::height) and number of columns (CvSize::width) of the input matrix or image. In case of image the size of ROI is returned.


InitSparseMatIterator

Initializes sparse array elements iterator

CvSparseNode* cvInitSparseMatIterator( const CvSparseMat* mat,
                                       CvSparseMatIterator* mat_iterator );

mat
Input array.
mat_iterator
Initialized iterator.

The function cvInitSparseMatIterator initializes iterator of sparse array elements and returns pointer to the first element, or NULL if the array is empty.


GetNextSparseNode

Initializes sparse array elements iterator

CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator );

mat_iterator
Sparse array iterator.

The function cvGetNextSparseNode moves iterator to the next sparse matrix element and returns pointer to it. In the current version there is no any particular order of the elements, because they are stored in hash table. The sample below demonstrates how to iterate through the sparse matrix:

Using cvInitSparseMatIterator and cvGetNextSparseNode to calculate sum of floating-point sparse array.

    double sum;
    int i, dims = cvGetDims( array );
    CvSparseMatIterator mat_iterator;
    CvSparseNode* node = cvInitSparseMatIterator( array, &mat_iterator );

    for( ; node != 0; node = cvGetNextSparseNode( &mat_iterator ))
    {
        const int* idx = CV_NODE_IDX( array, node ); /* get pointer to the element indices */
        float val = *(float*)CV_NODE_VAL( array, node ); /* get value of the element
                                                          (assume that the type is CV_32FC1) */
        printf( "(" );
        for( i = 0; i < dims; i++ )
            printf( "%4d%s", idx[i], i < dims - 1 "," : "): " );
        printf( "%g\n", val );

        sum += val;
    }

    printf( "\nTotal sum = %g\n", sum );


GetElemType

Returns type of array elements

int cvGetElemType( const CvArr* arr );

arr
Input array.

The functions GetElemType returns type of the array elements as it is described in cvCreateMat discussion:

CV_8UC1 ... CV_64FC4


GetDims, GetDimSize

Return number of array dimensions and their sizes or the size of particular dimension

int cvGetDims( const CvArr* arr, int* sizes=NULL );
int cvGetDimSize( const CvArr* arr, int index );

arr
Input array.
sizes
Optional output vector of the array dimension sizes. For 2d arrays the number of rows (height) goes first, number of columns (width) next.
index
Zero-based dimension index (for matrices 0 means number of rows, 1 means number of columns; for images 0 means height, 1 means width).

The function cvGetDims returns number of array dimensions and their sizes. In case of IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. The function cvGetDimSize returns the particular dimension size (number of elements per that dimension). For example, the following code calculates total number of array elements in two ways:


// via cvGetDims()
int sizes[CV_MAX_DIM];
int i, total = 1;
int dims = cvGetDims( arr, size );
for( i = 0; i < dims; i++ )
    total *= sizes[i];

// via cvGetDims() and cvGetDimSize()
int i, total = 1;
int dims = cvGetDims( arr );
for( i = 0; i < dims; i++ )
    total *= cvGetDimsSize( arr, i );


Ptr*D

Return pointer to the particular array element

uchar* cvPtr1D( const CvArr* arr, int idx0, int* type=NULL );
uchar* cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type=NULL );
uchar* cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, int* type=NULL );
uchar* cvPtrND( const CvArr* arr, const int* idx, int* type=NULL, int create_node=1, unsigned* precalc_hashval=NULL );

arr
Input array.
idx0
The first zero-based component of the element index
idx1
The second zero-based component of the element index
idx2
The third zero-based component of the element index
idx
Array of the element indices
type
Optional output parameter: type of matrix elements
create_node
Optional input parameter for sparse matrices. Non-zero value of the parameter means that the requested element is created if it does not exist already.
precalc_hashval
Optional input parameter for sparse matrices. If the pointer is not NULL, the function does not recalculate the node hash value, but takes it from the specified location. It is useful for speeding up pair-wise operations (TODO: provide an example)

The functions >cvPtr*D return pointer to the particular array element. Number of array dimension should match to the number of indices passed to the function except for cvPtr1D function that can be used for sequential access to 1D, 2D or nD dense arrays.

The functions can be used for sparse arrays as well - if the requested node does not exist they create it and set it to zero.

All these as well as other functions accessing array elements (cvGet*D, cvGetReal*D, cvSet*D, cvSetReal*D) raise an error in case if the element index is out of range.


Get*D

Return the particular array element

CvScalar cvGet1D( const CvArr* arr, int idx0 );
CvScalar cvGet2D( const CvArr* arr, int idx0, int idx1 );
CvScalar cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 );
CvScalar cvGetND( const CvArr* arr, const int* idx );

arr
Input array.
idx0
The first zero-based component of the element index
idx1
The second zero-based component of the element index
idx2
The third zero-based component of the element index
idx
Array of the element indices

The functions cvGet*D return the particular array element. In case of sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions)


GetReal*D

Return the particular element of single-channel array

double cvGetReal1D( const CvArr* arr, int idx0 );
double cvGetReal2D( const CvArr* arr, int idx0, int idx1 );
double cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 );
double cvGetRealND( const CvArr* arr, const int* idx );

arr
Input array. Must have a single channel.
idx0
The first zero-based component of the element index
idx1
The second zero-based component of the element index
idx2
The third zero-based component of the element index
idx
Array of the element indices

The functions cvGetReal*D return the particular element of single-channel array. If the array has multiple channels, runtime error is raised. Note that cvGet*D function can be used safely for both single-channel and multiple-channel arrays though they are a bit slower.

In case of sparse array the functions return 0 if the requested node does not exist (no new node is created by the functions)


mGet

Return the particular element of single-channel floating-point matrix

double cvmGet( const CvMat* mat, int row, int col );

mat
Input matrix.
row
The zero-based index of row.
col
The zero-based index of column.

The function cvmGet is a fast replacement for cvGetReal2D in case of single-channel floating-point matrices. It is faster because it is inline, it does less checks for array type and array element type and it checks for the row and column ranges only in debug mode.


Set*D

Change the particular array element

void cvSet1D( CvArr* arr, int idx0, CvScalar value );
void cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value );
void cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value );
void cvSetND( CvArr* arr, const int* idx, CvScalar value );

arr
Input array.
idx0
The first zero-based component of the element index
idx1
The second zero-based component of the element index
idx2
The third zero-based component of the element index
idx
Array of the element indices
value
The assigned value

The functions cvSet*D assign the new value to the particular element of array. In case of sparse array the functions create the node if it does not exist yet


SetReal*D

Change the particular array element

void cvSetReal1D( CvArr* arr, int idx0, double value );
void cvSetReal2D( CvArr* arr, int idx0, int idx1, double value );
void cvSetReal3D( CvArr* arr, int idx0, int idx1, int idx2, double value );
void cvSetRealND( CvArr* arr, const int* idx, double value );

arr
Input array.
idx0
The first zero-based component of the element index
idx1
The second zero-based component of the element index
idx2
The third zero-based component of the element index
idx
Array of the element indices
value
The assigned value

The functions cvSetReal*D assign the new value to the particular element of single-channel array. If the array has multiple channels, runtime error is raised. Note that cvSet*D function can be used safely for both single-channel and multiple-channel arrays though they are a bit slower.

In case of sparse array the functions create the node if it does not exist yet


mSet

Return the particular element of single-channel floating-point matrix

void cvmSet( CvMat* mat, int row, int col, double value );

mat
The matrix.
row
The zero-based index of row.
col
The zero-based index of column.
value
The new value of the matrix element

The function cvmSet is a fast replacement for cvSetReal2D in case of single-channel floating-point matrices. It is faster because it is inline, it does less checks for array type and array element type and it checks for the row and column ranges only in debug mode.


ClearND

Clears the particular array element

void cvClearND( CvArr* arr, const int* idx );

arr
Input array.
idx
Array of the element indices

The function cvClearND clears (sets to zero) the particular element of dense array or deletes the element of sparse array. If the element does not exists, the function does nothing.


Copying and Filling


Copy

Copies one array to another

void cvCopy( const CvArr* src, CvArr* dst, const CvArr* mask=NULL );

src
The source array.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvCopy copies selected elements from input array to output array:

dst(I)=src(I) if mask(I)!=0.

If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays must have the same type, the same number of dimensions and the same size. The function can also copy sparse arrays (mask is not supported in this case).


Set

Sets every element of array to given value

void cvSet( CvArr* arr, CvScalar value, const CvArr* mask=NULL );

arr
The destination array.
value
Fill value.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvSet copies scalar value to every selected element of the destination array:

arr(I)=value if mask(I)!=0

If array arr is of IplImage type, then is ROI used, but COI must not be set.


SetZero

Clears the array

void cvSetZero( CvArr* arr );
#define cvZero cvSetZero

arr
array to be cleared.

The function cvSetZero clears the array. In case of dense arrays (CvMat, CvMatND or IplImage) cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0), in case of sparse arrays all the elements are removed.


SetIdentity

Initializes scaled identity matrix

void cvSetIdentity( CvArr* mat, CvScalar value=cvRealScalar(1) );

arr
The matrix to initialize (not necesserily square).
value
The value to assign to the diagonal elements.

The function cvSetIdentity initializes scaled identity matrix:

arr(i,j)=value if i=j,
       0 otherwise

Range

Fills matrix with given range of numbers

void cvRange( CvArr* mat, double start, double end );

mat
The matrix to initialize. It should be single-channel 32-bit, integer or floating-point.
start
The lower inclusive boundary of the range.
end
The upper exclusive boundary of the range.

The function cvRange initializes the matrix as following:

arr(i,j)=(end-start)*(i*cols(arr)+j)/(cols(arr)*rows(arr))
For example, the following code will initilize 1D vector with subsequent integer numbers.
CvMat* A = cvCreateMat( 1, 10, CV_32S );
cvRange( A, 0, A->cols ); // A will be initialized as [0,1,2,3,4,5,6,7,8,9]

Transforms and Permutations


Reshape

Changes shape of matrix/image without copying data

CvMat* cvReshape( const CvArr* arr, CvMat* header, int new_cn, int new_rows=0 );

arr
Input array.
header
Output header to be filled.
new_cn
New number of channels. new_cn = 0 means that number of channels remains unchanged.
new_rows
New number of rows. new_rows = 0 means that number of rows remains unchanged unless it needs to be changed according to new_cn value. destination array to be changed.

The function cvReshape initializes CvMat header so that it points to the same data as the original array but has different shape - different number of channels, different number of rows or both.

For example, the following code creates one image buffer and two image headers, first is for 320x240x3 image and the second is for 960x240x1 image:

IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
CvMat gray_mat_hdr;
IplImage gray_img_hdr, *gray_img;
cvReshape( color_img, &gray_mat_hdr, 1 );
gray_img = cvGetImage( &gray_mat_hdr, &gray_img_hdr );

And the next example converts 3x3 matrix to a single 1x9 vector

CvMat* mat = cvCreateMat( 3, 3, CV_32F );
CvMat row_header, *row;
row = cvReshape( mat, &row_header, 0, 1 );

ReshapeMatND

Changes shape of multi-dimensional array w/o copying data

CvArr* cvReshapeMatND( const CvArr* arr,
                       int sizeof_header, CvArr* header,
                       int new_cn, int new_dims, int* new_sizes );

#define cvReshapeND( arr, header, new_cn, new_dims, new_sizes )   \
      cvReshapeMatND( (arr), sizeof(*(header)), (header),         \
                      (new_cn), (new_dims), (new_sizes))

arr
Input array.
sizeof_header
Size of output header to distinguish between IplImage, CvMat and CvMatND output headers.
header
Output header to be filled.
new_cn
New number of channels. new_cn = 0 means that number of channels remains unchanged.
new_dims
New number of dimensions. new_dims = 0 means that number of dimensions remains the same.
new_sizes
Array of new dimension sizes. Only new_dims-1 values are used, because the total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not used

The function cvReshapeMatND is an advanced version of cvReshape that can work with multi-dimensional arrays as well (though, it can work with ordinary images and matrices) and change the number of dimensions. Below are the two samples from the cvReshape description rewritten using cvReshapeMatND:

IplImage* color_img = cvCreateImage( cvSize(320,240), IPL_DEPTH_8U, 3 );
IplImage gray_img_hdr, *gray_img;
gray_img = (IplImage*)cvReshapeND( color_img, &gray_img_hdr, 1, 0, 0 );

...

/* second example is modified to convert 2x2x2 array to 8x1 vector */
int size[] = { 2, 2, 2 };
CvMatND* mat = cvCreateMatND( 3, size, CV_32F );
CvMat row_header, *row;
row = cvReshapeND( mat, &row_header, 0, 1, 0 );

Repeat

Fill destination array with tiled source array

void cvRepeat( const CvArr* src, CvArr* dst );

src
Source array, image or matrix.
dst
Destination array, image or matrix.

The function cvRepeat fills the destination array with source array tiled:

dst(i,j)=src(i mod rows(src), j mod cols(src))

So the destination array may be as larger as well as smaller than the source array.


Flip

Flip a 2D array around vertical, horizontall or both axises

void  cvFlip( const CvArr* src, CvArr* dst=NULL, int flip_mode=0);
#define cvMirror cvFlip

src
Source array.
dst
Destination array. If dst = NULL the flipping is done inplace.
flip_mode
Specifies how to flip the array.
flip_mode = 0 means flipping around x-axis, flip_mode > 0 (e.g. 1) means flipping around y-axis and flip_mode < 0 (e.g. -1) means flipping around both axises. See also the discussion below for the formulas

The function cvFlip flips the array in one of different 3 ways (row and column indices are 0-based):

dst(i,j)=src(rows(src)-i-1,j) if flip_mode = 0
dst(i,j)=src(i,cols(src1)-j-1) if flip_mode > 0
dst(i,j)=src(rows(src)-i-1,cols(src)-j-1) if flip_mode < 0

The example cenaria of the function use are:


Split

Divides multi-channel array into several single-channel arrays or extracts a single channel from the array

void cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1,
              CvArr* dst2, CvArr* dst3 );
#define cvCvtPixToPlane cvSplit

src
Source array.
dst0...dst3
Destination channels.

The function cvSplit divides a multi-channel array into separate single-channel arrays. Two modes are available for the operation. If the source array has N channels then if the first N destination channels are not NULL, all they are extracted from the source array, otherwise if only a single destination channel of the first N is not NULL, this particular channel is extracted, otherwise an error is raised. Rest of destination channels (beyond the first N) must always be NULL. For IplImage cvCopy with COI set can be also used to extract a single channel from the image.


Merge

Composes multi-channel array from several single-channel arrays or inserts a single channel into the array

void cvMerge( const CvArr* src0, const CvArr* src1,
              const CvArr* src2, const CvArr* src3, CvArr* dst );
#define cvCvtPlaneToPix cvMerge

src0... src3
Input channels.
dst
Destination array.

The function cvMerge is the opposite to the previous. If the destination array has N channels then if the first N input channels are not NULL, all they are copied to the destination array, otherwise if only a single source channel of the first N is not NULL, this particular channel is copied into the destination array, otherwise an error is raised. Rest of source channels (beyond the first N) must always be NULL. For IplImage cvCopy with COI set can be also used to insert a single channel into the image.


MixChannels

Copies several channels from input arrays to certain channels of output arrays

void cvMixChannels( const CvArr** src, int src_count,
                    CvArr** dst, int dst_count,
                    const int* from_to, int pair_count );

src
The array of input arrays.
src_count
The number of input arrays.
dst
The array of output arrays.
dst_count
The number of output arrays.
from_to
The array of pairs of indices of the planes copied. from_to[k*2] is the 0-based index of the input plane, and from_to[k*2+1] is the index of the output plane, where the continuous numbering of the planes over all the input and over all the output arrays is used. When from_to[k*2] is negative, the corresponding output plane is filled with 0's.
pair_count
The number of pairs in from_to, or the number of the planes copied.

The function cvMixChannels is a generalized form of cvSplit and cvMerge and some forms of cvCvtColor. It can be used to change the order of the planes, add/remove alpha channel, extract or insert a single plane or multiple planes etc. Below is the example, how to split 4-channel RGBA image into 3-channel BGR (i.e. with R&B swapped) and separate alpha channel images:

    CvMat* rgba = cvCreateMat( 100, 100, CV_8UC4 );
    CvMat* bgr = cvCreateMat( rgba->rows, rgba->cols, CV_8UC3 );
    CvMat* alpha = cvCreateMat( rgba->rows, rgba->cols, CV_8UC1 );
    CvArr* out[] = { bgr, alpha };
    int from_to[] = { 0, 2, 1, 1, 2, 0, 3, 3 };
    cvSet( rgba, cvScalar(1,2,3,4) );
    cvMixChannels( (const CvArr**)&rgba, 1, out, 2, from_to, 4 );

RandShuffle

Randomly shuffles the array elements

void cvRandShuffle( CvArr* mat, CvRNG* rng, double iter_factor=1. );

mat
The input/output matrix. It is shuffled in-place.
rng
The Random Number Generator used to shuffle the elements. When the pointer is NULL, a temporary RNG will be created and used.
iter_factor
The relative parameter that characterizes intensity of the shuffling performed. See the description below.

The function cvRandShuffle shuffles the matrix by swapping randomly chosen pairs of the matrix elements on each iteration (where each element may contain several components in case of multi-channel arrays). The number of iterations (i.e. pairs swapped) is round(iter_factor*rows(mat)*cols(mat)), so iter_factor=0 means that no shuffling is done, iter_factor=1 means that the function swaps rows(mat)*cols(mat) random pairs etc.


Arithmetic, Logic and Comparison


LUT

Performs look-up table transform of array

void cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut );

src
Source array of 8-bit elements.
dst
Destination array of arbitrary depth and of the same number of channels as the source array.
lut
Look-up table of 256 elements; should have the same depth as the destination array. In case of multi-channel source and destination arrays, the table should either have a single-channel (in this case the same table is used for all channels), or the same number of channels as the source/destination array.

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 following:

dst(I)=lut[src(I)+DELTA]
where DELTA=0 if src has depth CV_8U, and DELTA=128 if src has depth CV_8S.


ConvertScale

Converts one array to another with optional linear transformation

void cvConvertScale( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );

#define cvCvtScale cvConvertScale
#define cvScale  cvConvertScale
#define cvConvert( src, dst )  cvConvertScale( (src), (dst), 1, 0 )

src
Source array.
dst
Destination array.
scale
Scale factor.
shift
Value added to the scaled source array elements.

The function cvConvertScale has several different purposes and thus has several synonyms. It copies one array to another with optional scaling, which is performed first, and/or optional type conversion, performed after:

dst(I)=src(I)*scale + (shift,shift,...)

All the channels of multi-channel arrays are processed independently.

The type conversion is done with rounding and saturation, that is if a result of scaling + conversion can not be represented exactly by a value of destination array element type, it is set to the nearest representable value on the real axis.

In case of scale=1, shift=0 no prescaling is done. This is a specially optimized case and it has the appropriate cvConvert synonym. If source and destination array types have equal types, this is also a special case that can be used to scale and shift a matrix or an image and that fits to cvScale synonym.


ConvertScaleAbs

Converts input array elements to 8-bit unsigned integer another with optional linear transformation

void cvConvertScaleAbs( const CvArr* src, CvArr* dst, double scale=1, double shift=0 );
#define cvCvtScaleAbs cvConvertScaleAbs

src
Source array.
dst
Destination array (should have 8u depth).
scale
ScaleAbs factor.
shift
Value added to the scaled source array elements.

The function cvConvertScaleAbs is similar to the previous one, but it stores absolute values of the conversion results:

dst(I)=abs(src(I)*scale + (shift,shift,...))

The function supports only destination arrays of 8u (8-bit unsigned integers) type, for other types the function can be emulated by combination of cvConvertScale and cvAbs functions.


Add

Computes per-element sum of two arrays

void cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );

src1
The first source array.
src2
The second source array.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvAdd adds one array to another one:

dst(I)=src1(I)+src2(I) if mask(I)!=0

All the arrays must have the same type, except the mask, and the same size (or ROI size)


AddS

Computes sum of array and scalar

void cvAddS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );

src
The source array.
value
Added scalar.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvAddS adds scalar value to every element in the source array src1 and stores the result in dst

dst(I)=src(I)+value if mask(I)!=0

All the arrays must have the same type, except the mask, and the same size (or ROI size)


AddWeighted

Computes weighted sum of two arrays

void  cvAddWeighted( const CvArr* src1, double alpha,
                     const CvArr* src2, double beta,
                     double gamma, CvArr* dst );

src1
The first source array.
alpha
Weight of the first array elements.
src2
The second source array.
beta
Weight of the second array elements.
dst
The destination array.
gamma
Scalar, added to each sum.

The function cvAddWeighted calculated weighted sum of two arrays as following:

dst(I)=src1(I)*alpha+src2(I)*beta+gamma

All the arrays must have the same type and the same size (or ROI size)


Sub

Computes per-element difference between two arrays

void cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );

src1
The first source array.
src2
The second source array.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvSub subtracts one array from another one:

dst(I)=src1(I)-src2(I) if mask(I)!=0

All the arrays must have the same type, except the mask, and the same size (or ROI size)


SubS

Computes difference between array and scalar

void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );

src
The source array.
value
Subtracted scalar.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvSubS subtracts a scalar from every element of the source array:

dst(I)=src(I)-value if mask(I)!=0

All the arrays must have the same type, except the mask, and the same size (or ROI size)


SubRS

Computes difference between scalar and array

void cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );

src
The first source array.
value
Scalar to subtract from.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvSubRS subtracts every element of source array from a scalar:

dst(I)=value-src(I) if mask(I)!=0

All the arrays must have the same type, except the mask, and the same size (or ROI size)


Mul

Calculates per-element product of two arrays

void cvMul( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );

src1
The first source array.
src2
The second source array.
dst
The destination array.
scale
Optional scale factor

The function cvMul calculates per-element product of two arrays:

dst(I)=scale•src1(I)•src2(I)

All the arrays must have the same type, and the same size (or ROI size)


Div

Performs per-element division of two arrays

void cvDiv( const CvArr* src1, const CvArr* src2, CvArr* dst, double scale=1 );

src1
The first source array. If the pointer is NULL, the array is assumed to be all 1’s.
src2
The second source array.
dst
The destination array.
scale
Optional scale factor

The function cvDiv divides one array by another:

dst(I)=scale•src1(I)/src2(I), if src1!=NULL
dst(I)=scale/src2(I),      if src1=NULL

All the arrays must have the same type, and the same size (or ROI size)


And

Calculates per-element bit-wise conjunction of two arrays

void cvAnd( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );

src1
The first source array.
src2
The second source array.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvAnd calculates per-element bit-wise logical conjunction of two arrays:

dst(I)=src1(I)&src2(I) if mask(I)!=0

In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size


AndS

Calculates per-element bit-wise conjunction of array and scalar

void cvAndS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );

src
The source array.
value
Scalar to use in the operation.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function AndS calculates per-element bit-wise conjunction of array and scalar:

dst(I)=src(I)&value if mask(I)!=0

Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size

The following sample demonstrates how to calculate absolute value of floating-point array elements by clearing the most-significant bit:

float a[] = { -1, 2, -3, 4, -5, 6, -7, 8, -9 };
CvMat A = cvMat( 3, 3, CV_32F, &a );
int i, abs_mask = 0x7fffffff;
cvAndS( &A, cvRealScalar(*(float*)&abs_mask), &A, 0 );
for( i = 0; i < 9; i++ )
    printf("%.1f ", a[i] );

The code should print:

1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0

Or

Calculates per-element bit-wise disjunction of two arrays

void cvOr( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );

src1
The first source array.
src2
The second source array.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvOr calculates per-element bit-wise disjunction of two arrays:

dst(I)=src1(I)|src2(I)

In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size


OrS

Calculates per-element bit-wise disjunction of array and scalar

void cvOrS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );

src1
The source array.
value
Scalar to use in the operation.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function OrS calculates per-element bit-wise disjunction of array and scalar:

dst(I)=src(I)|value if mask(I)!=0

Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size


Xor

Performs per-element bit-wise "exclusive or" operation on two arrays

void cvXor( const CvArr* src1, const CvArr* src2, CvArr* dst, const CvArr* mask=NULL );

src1
The first source array.
src2
The second source array.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function cvXor calculates per-element bit-wise logical conjunction of two arrays:

dst(I)=src1(I)^src2(I) if mask(I)!=0

In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size


XorS

Performs per-element bit-wise "exclusive or" operation on array and scalar

void cvXorS( const CvArr* src, CvScalar value, CvArr* dst, const CvArr* mask=NULL );

src
The source array.
value
Scalar to use in the operation.
dst
The destination array.
mask
Operation mask, 8-bit single channel array; specifies elements of destination array to be changed.

The function XorS calculates per-element bit-wise conjunction of array and scalar:

dst(I)=src(I)^value if mask(I)!=0

Prior to the actual operation the scalar is converted to the same type as the arrays. In the case of floating-point arrays their bit representations are used for the operation. All the arrays must have the same type, except the mask, and the same size

The following sample demonstrates how to conjugate complex vector by switching the most-significant bit of imaging part:

float a[] = { 1, 0, 0, 1, -1, 0, 0, -1 }; /* 1, j, -1, -j */
CvMat A = cvMat( 4, 1, CV_32FC2, &a );
int i, neg_mask = 0x80000000;
cvXorS( &A, cvScalar( 0, *(float*)&neg_mask, 0, 0 ), &A, 0 );
for( i = 0; i < 4; i++ )
    printf("(%.1f, %.1f) ", a[i*2], a[i*2+1] );

The code should print:

(1.0,0.0) (0.0,-1.0) (-1.0,0.0) (0.0,1.0)

Not

Performs per-element bit-wise inversion of array elements

void cvNot( const CvArr* src, CvArr* dst );

src1
The source array.
dst
The destination array.

The function Not inverses every bit of every array element:

dst(I)=~src(I)

Cmp

Performs per-element comparison of two arrays

void cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op );

src1
The first source array.
src2
The second source array. Both source array must have a single channel.
dst
The destination array, must have 8u or 8s type.
cmp_op
The flag specifying the relation between the elements to be checked:
CV_CMP_EQ - src1(I) "equal to" src2(I)
CV_CMP_GT - src1(I) "greater than" src2(I)
CV_CMP_GE - src1(I) "greater or equal" src2(I)
CV_CMP_LT - src1(I) "less than" src2(I)
CV_CMP_LE - src1(I) "less or equal" src2(I)
CV_CMP_NE - src1(I) "not equal to" src2(I)

The function cvCmp compares the corresponding elements of two arrays and fills the destination mask array:

dst(I)=src1(I) op src2(I),

where op is '=', '>', '>=', '<', '<=' or '!='.

dst(I) is set to 0xff (all '1'-bits) if the particular relation between the elements is true and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size)


CmpS

Performs per-element comparison of array and scalar

void cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op );

src
The source array, must have a single channel.
value
The scalar value to compare each array element with.
dst
The destination array, must have 8u or 8s type.
cmp_op
The flag specifying the relation between the elements to be checked:
CV_CMP_EQ - src1(I) "equal to" value
CV_CMP_GT - src1(I) "greater than" value
CV_CMP_GE - src1(I) "greater or equal" value
CV_CMP_LT - src1(I) "less than" value
CV_CMP_LE - src1(I) "less or equal" value
CV_CMP_NE - src1(I) "not equal" value

The function cvCmpS compares the corresponding elements of array and scalar and fills the destination mask array:

dst(I)=src(I) op scalar,

where op is '=', '>', '>=', '<', '<=' or '!='.

dst(I) is set to 0xff (all '1'-bits) if the particular relation between the elements is true and 0 otherwise. All the arrays must have the same size (or ROI size)


InRange

Checks that array elements lie between elements of two other arrays

void cvInRange( const CvArr* src, const CvArr* lower, const CvArr* upper, CvArr* dst );

src
The first source array.
lower
The inclusive lower boundary array.
upper
The exclusive upper boundary array.
dst
The destination array, must have 8u or 8s type.

The function cvInRange does the range check for every element of the input array:

dst(I)=lower(I)0 <= src(I)0 < upper(I)0

for single-channel arrays,

dst(I)=lower(I)0 <= src(I)0 < upper(I)0 &&
     lower(I)1 <= src(I)1 < upper(I)1

for two-channel arrays etc.

dst(I) is set to 0xff (all '1'-bits) if src(I) is within the range and 0 otherwise. All the arrays must have the same type, except the destination, and the same size (or ROI size)


InRangeS

Checks that array elements lie between two scalars

void cvInRangeS( const CvArr* src, CvScalar lower, CvScalar upper, CvArr* dst );

src
The first source array.
lower
The inclusive lower boundary.
upper
The exclusive upper boundary.
dst
The destination array, must have 8u or 8s type.

The function cvInRangeS does the range check for every element of the input array:

dst(I)=lower0 <= src(I)0 < upper0

for a single-channel array,

dst(I)=lower0 <= src(I)0 < upper0 &&
     lower1 <= src(I)1 < upper1

for a two-channel array etc.

dst(I) is set to 0xff (all '1'-bits) if src(I) is within the range and 0 otherwise. All the arrays must have the same size (or ROI size)


Max

Finds per-element maximum of two arrays

void cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst );

src1
The first source array.
src2
The second source array.
dst
The destination array.

The function cvMax calculates per-element maximum of two arrays:

dst(I)=max(src1(I), src2(I))

All the arrays must have a single channel, the same data type and the same size (or ROI size).


MaxS

Finds per-element maximum of array and scalar

void cvMaxS( const CvArr* src, double value, CvArr* dst );

src
The first source array.
value
The scalar value.
dst
The destination array.

The function cvMaxS calculates per-element maximum of array and scalar:

dst(I)=max(src(I), value)

All the arrays must have a single channel, the same data type and the same size (or ROI size).


Min

Finds per-element minimum of two arrays

void cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst );

src1
The first source array.
src2
The second source array.
dst
The destination array.

The function cvMin calculates per-element minimum of two arrays:

dst(I)=min(src1(I),src2(I))

All the arrays must have a single channel, the same data type and the same size (or ROI size).


MinS

Finds per-element minimum of array and scalar

void cvMinS( const CvArr* src, double value, CvArr* dst );

src
The first source array.
value
The scalar value.
dst
The destination array.

The function cvMinS calculates minimum of array and scalar:

dst(I)=min(src(I), value)

All the arrays must have a single channel, the same data type and the same size (or ROI size).


AbsDiff

Calculates absolute difference between two arrays

void cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst );

src1
The first source array.
src2
The second source array.
dst
The destination array.

The function cvAbsDiff calculates absolute difference between two arrays.

dst(I)c = abs(src1(I)c - src2(I)c).

All the arrays must have the same data type and the same size (or ROI size).


AbsDiffS

Calculates absolute difference between array and scalar

void cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value );
#define cvAbs(src, dst) cvAbsDiffS(src, dst, cvScalarAll(0))

src
The source array.
dst
The destination array.
value
The scalar.

The function cvAbsDiffS calculates absolute difference between array and scalar.

dst(I)c = abs(src(I)c - valuec).

All the arrays must have the same data type and the same size (or ROI size).


Statistics


CountNonZero

Counts non-zero array elements

int cvCountNonZero( const CvArr* arr );

arr
The array, must be single-channel array or multi-channel image with COI set.

The function cvCountNonZero returns the number of non-zero elements in src1:

result = sumI arr(I)!=0
In case of IplImage both ROI and COI are supported.


Sum

Summarizes array elements

CvScalar cvSum( const CvArr* arr );

arr
The array.

The function cvSum calculates sum S of array elements, independently for each channel:

Sc = sumI arr(I)c
If the array is IplImage and COI is set, the function processes the selected channel only and stores the sum to the first scalar component (S0).


Avg

Calculates average (mean) of array elements

CvScalar cvAvg( const CvArr* arr, const CvArr* mask=NULL );

arr
The array.
mask
The optional operation mask.

The function cvAvg calculates the average value M of array elements, independently for each channel:

N = sumI mask(I)!=0

Mc = 1/N • sumI,mask(I)!=0 arr(I)c
If the array is IplImage and COI is set, the function processes the selected channel only and stores the average to the first scalar component (S0).


AvgSdv

Calculates average (mean) of array elements

void cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, const CvArr* mask=NULL );

arr
The array.
mean
Pointer to the mean value, may be NULL if it is not needed.
std_dev
Pointer to the standard deviation.
mask
The optional operation mask.

The function cvAvgSdv calculates the average value and standard deviation of array elements, independently for each channel:

N = sumI mask(I)!=0

meanc = 1/N • sumI,mask(I)!=0 arr(I)c

std_devc = sqrt(1/N • sumI,mask(I)!=0 (arr(I)c - Mc)2)
If the array is IplImage and COI is set, the function processes the selected channel only and stores the average and standard deviation to the first compoenents of output scalars (M0 and S0).


MinMaxLoc

Finds global minimum and maximum in array or subarray

void cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val,
                  CvPoint* min_loc=NULL, CvPoint* max_loc=NULL, const CvArr* mask=NULL );

arr
The source array, single-channel or multi-channel with COI set.
min_val
Pointer to returned minimum value.
max_val
Pointer to returned maximum value.
min_loc
Pointer to returned minimum location.
max_loc
Pointer to returned maximum location.
mask
The optional mask that is used to select a subarray.

The function MinMaxLoc finds minimum and maximum element values and their positions. The extremums are searched over the whole array, selected ROI (in case of IplImage) or, if mask is not NULL, in the specified array region. If the array has more than one channel, it must be IplImage with COI set. In case if multi-dimensional arrays min_loc->x and max_loc->x will contain raw (linear) positions of the extremums.


Norm

Calculates absolute array norm, absolute difference norm or relative difference norm

double cvNorm( const CvArr* arr1, const CvArr* arr2=NULL, int norm_type=CV_L2, const CvArr* mask=NULL );

arr1
The first source image.
arr2
The second source image. If it is NULL, the absolute norm of arr1 is calculated, otherwise absolute or relative norm of arr1-arr2 is calculated.
normType
Type of norm, see the discussion.
mask
The optional operation mask.

The function cvNorm calculates the absolute norm of arr1 if arr2 is NULL:

norm = ||arr1||C = maxI abs(arr1(I)),  if normType = CV_C

norm = ||arr1||L1 = sumI abs(arr1(I)),  if normType = CV_L1

norm = ||arr1||L2 = sqrt( sumI arr1(I)2),  if normType = CV_L2

And the function calculates absolute or relative difference norm if arr2 is not NULL:

norm = ||arr1-arr2||C = maxI abs(arr1(I)-arr2(I)),  if normType = CV_C

norm = ||arr1-arr2||L1 = sumI abs(arr1(I)-arr2(I)),  if normType = CV_L1

norm = ||arr1-arr2||L2 = sqrt( sumI (arr1(I)-arr2(I))2 ),  if normType = CV_L2

or

norm = ||arr1-arr2||C/||arr2||C, if normType = CV_RELATIVE_C

norm = ||arr1-arr2||L1/||arr2||L1, if normType = CV_RELATIVE_L1

norm = ||arr1-arr2||L2/||arr2||L2, if normType = CV_RELATIVE_L2

The function Norm returns the calculated norm. The multiple-channel array are treated as single-channel, that is, the results for all channels are combined.


Reduce

Reduces matrix to a vector

void cvReduce( const CvArr* src, CvArr* dst, int op=CV_REDUCE_SUM );

src
The input matrix.
dst
The output single-row/single-column vector that accumulates somehow all the matrix rows/columns.
dim
The dimension index along which the matrix is reduce. 0 means that the matrix is reduced to a single row, 1 means that the matrix is reduced to a single column. -1 means that the dimension is chosen automatically by analysing the dst size.
op
The reduction operation. It can take of the following values:
CV_REDUCE_SUM - the output is the sum of all the matrix rows/columns.
CV_REDUCE_AVG - the output is the mean vector of all the matrix rows/columns.
CV_REDUCE_MAX - the output is the maximum (column/row-wise) of all the matrix rows/columns.
CV_REDUCE_MIN - the output is the minimum (column/row-wise) of all the matrix rows/columns.

The function cvReduce 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 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.


Linear Algebra


DotProduct

Calculates dot product of two arrays in Euclidian metrics

double cvDotProduct( const CvArr* src1, const CvArr* src2 );

src1
The first source array.
src2
The second source array.

The function cvDotProduct calculates and returns the Euclidean dot product of two arrays.

src1•src2 = sumI(src1(I)*src2(I))

In case of multiple channel arrays the results for all channels are accumulated. In particular, cvDotProduct(a,a), where a is a complex vector, will return ||a||2. The function can process multi-dimensional arrays, row by row, layer by layer and so on.


Normalize

Normalizes array to a certain norm or value range

void cvNormalize( const CvArr* src, CvArr* dst,
                  double a=1, double b=0, int norm_type=CV_L2,
                  const CvArr* mask=NULL );

src
The input array.
dst
The output array; in-place operation is supported.
a
The minimum/maximum value of the output array or the norm of output array.
b
The maximum/minimum value of the output array.
norm_type
The normalization type. It can take one of the following values:
CV_C - the C-norm (maximum of absolute values) of the array is normalized.
CV_L1 - the L1-norm (sum of absolute values) of the array is normalized.
CV_L2 - the (Euclidian) L2-norm of the array is normalized.
CV_MINMAX - the array values are scaled and shifted to the specified range.
mask
The operation mask. Makes the function consider and normalize only certain array elements.

The function cvNormalize normalizes the input array so that it's norm or value range takes the certain value(s).

When norm_type==CV_MINMAX:

    dst(i,j)=(src(i,j)-min(src))*(b'-a')/(max(src)-min(src)) + a',  if mask(i,j)!=0
    dst(i,j)=src(i,j)  otherwise
where b'=MAX(a,b), a'=MIN(a,b);
min(src) and max(src) are the global minimum and maximum, respectively, of the input array, computed over the whole array or the specified subset of it.

When norm_type!=CV_MINMAX:

    dst(i,j)=src(i,j)*a/cvNorm(src,0,norm_type,mask), if mask(i,j)!=0
    dst(i,j)=src(i,j)  otherwise

Here is the short example:

float v[3] = { 1, 2, 3 };
CvMat V = cvMat( 1, 3, CV_32F, v );

// make vector v unit-length;
// equivalent to
//   for(int i=0;i<3;i++) v[i]/=sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]);
cvNormalize( &V, &V );

CrossProduct

Calculates cross product of two 3D vectors

void cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst );

src1
The first source vector.
src2
The second source vector.
dst
The destination vector.

The function cvCrossProduct calculates the cross product of two 3D vectors:

dst = src1 × src2, (dst1 = src12src23 - src13src22 , dst2 = src13src21 - src11src23 , dst3 = src11src22 - src12src21).

ScaleAdd

Calculates sum of scaled array and another array

void cvScaleAdd( const CvArr* src1, CvScalar scale, const CvArr* src2, CvArr* dst );
#define cvMulAddS cvScaleAdd

src1
The first source array.
scale
Scale factor for the first array.
src2
The second source array.
dst
The destination array

The function cvScaleAdd calculates sum of scaled array and another array:

dst(I)=src1(I)*scale + src2(I)

All array parameters should have the same type and the same size.


GEMM

Performs generalized matrix multiplication

void  cvGEMM( const CvArr* src1, const CvArr* src2, double alpha,
              const CvArr* src3, double beta, CvArr* dst, int tABC=0 );
#define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( src1, src2, 1, src3, 1, dst, 0 )
#define cvMatMul( src1, src2, dst ) cvMatMulAdd( src1, src2, 0, dst )

src1
The first source array.
src2
The second source array.
src3
The third source array (shift). Can be NULL, if there is no shift.
dst
The destination array.
tABC
The operation flags that can be 0 or combination of the following values:
CV_GEMM_A_T - transpose src1
CV_GEMM_B_T - transpose src2
CV_GEMM_C_T - transpose src3
for example, CV_GEMM_A_T+CV_GEMM_C_T corresponds to
alpha*src1T*src2 + beta*srcT

The function cvGEMM performs generalized matrix multiplication:

dst = alpha*op(src1)*op(src2) + beta*op(src3), where op(X) is X or XT

All the matrices should have the same data type and the coordinated sizes. Real or complex floating-point matrices are supported


Transform

Performs matrix transform of every array element

void cvTransform( const CvArr* src, CvArr* dst, const CvMat* transmat, const CvMat* shiftvec=NULL );

src
The first source array.
dst
The destination array.
transmat
Transformation matrix.
shiftvec
Optional shift vector.

The function cvTransform performs matrix transformation of every element of array src and stores the results in dst:

dst(I)=transmat*src(I) + shiftvec   or   dst(I)k=sumj(transmat(k,j)*src(I)j) + shiftvec(k)

That is every element of N-channel array src is considered as N-element vector, which is transformed using matrix M×N matrix transmat and shift vector shiftvec into an element of M-channel array dst. There is an option to embedd shiftvec into transmat. In this case transmat should be M×N+1 matrix and the right-most column is treated as the shift vector.

Both source and destination arrays should have the same depth and the same size or selected ROI size. transmat and shiftvec should be real floating-point matrices.

The function may be used for geometrical transformation of ND point set, arbitrary linear color space transformation, shuffling the channels etc.


PerspectiveTransform

Performs perspective matrix transform of vector array

void cvPerspectiveTransform( const CvArr* src, CvArr* dst, const CvMat* mat );

src
The source three-channel floating-point array.
dst
The destination three-channel floating-point array.
mat
3×3 or 4×4 transformation matrix.

The function cvPerspectiveTransform transforms every element of src (by treating it as 2D or 3D vector) in the following way:

(x, y, z) -> (x’/w, y’/w, z’/w) or
(x, y) -> (x’/w, y’/w),

where
(x’, y’, z’, w’) = mat4x4*(x, y, z, 1) or
(x’, y’, w’) = mat3x3*(x, y, 1)

and w = w’   if w’!=0,
        inf  otherwise

MulTransposed

Calculates product of array and transposed array

void cvMulTransposed( const CvArr* src, CvArr* dst, int order, const CvArr* delta=NULL );

src
The source matrix.
dst
The destination matrix.
order
Order of multipliers.
delta
An optional array, subtracted from src before multiplication.

The function cvMulTransposed calculates the product of src and its transposition.

The function evaluates

dst=(src-delta)*(src-delta)T

if order=0, and

dst=(src-delta)T*(src-delta)

otherwise.


Trace

Returns trace of matrix

CvScalar cvTrace( const CvArr* mat );

mat
The source matrix.

The function cvTrace returns sum of diagonal elements of the matrix src1.

tr(src1)=sumimat(i,i)

Transpose

Transposes matrix

void cvTranspose( const CvArr* src, CvArr* dst );
#define cvT cvTranspose

src
The source matrix.
dst
The destination matrix.

The function cvTranspose transposes matrix src1:

dst(i,j)=src(j,i)

Note that no complex conjugation is done in case of complex matrix. Conjugation should be done separately: look at the sample code in cvXorS for example


Det

Returns determinant of matrix

double cvDet( const CvArr* mat );

mat
The source matrix.

The function cvDet returns determinant of the square matrix mat. The direct method is used for small matrices and Gaussian elimination is used for larger matrices. For symmetric positive-determined matrices it is also possible to run SVD with U=V=NULL and then calculate determinant as a product of the diagonal elements of W


Invert

Finds inverse or pseudo-inverse of matrix

double cvInvert( const CvArr* src, CvArr* dst, int method=CV_LU );
#define cvInv cvInvert

src
The source matrix.
dst
The destination matrix.
method
Inversion method:
CV_LU - Gaussian elimination with optimal pivot element chose
CV_SVD - Singular value decomposition (SVD) method
CV_SVD_SYM - SVD method for a symmetric positively-defined matrix

The function cvInvert inverts matrix src1 and stores the result in src2

In case of LU method the function returns src1 determinant (src1 must be square). If it is 0, the matrix is not inverted and src2 is filled with zeros.

In case of SVD methods the function returns the inversed condition number of src1 (ratio of the smallest singular value to the largest singular value) and 0 if src1 is all zeros. The SVD methods calculate a pseudo-inverse matrix if src1 is singular


Solve

Solves linear system or least-squares problem

int cvSolve( const CvArr* A, const CvArr* B, CvArr* X, int method=CV_LU );

A
The source matrix.
B
The right-hand part of the linear system.
X
The output solution.
method
The solution (matrix inversion) method:
CV_LU - Gaussian elimination with optimal pivot element chose
CV_SVD - Singular value decomposition (SVD) method
CV_SVD_SYM - SVD method for a symmetric positively-defined matrix.

The function cvSolve solves linear system or least-squares problem (the latter is possible with SVD methods):

dst = arg minX||A*X-B||

If CV_LU method is used, the function returns 1 if src1 is non-singular and 0 otherwise, in the latter case dst is not valid


SVD

Performs singular value decomposition of real floating-point matrix

void cvSVD( CvArr* A, CvArr* W, CvArr* U=NULL, CvArr* V=NULL, int flags=0 );

A
Source M×N matrix.
W
Resulting singular value matrix (M×N or N×N) or vector (N×1).
U
Optional left orthogonal matrix (M×M or M×N). If CV_SVD_U_T is specified, the number of rows and columns in the sentence above should be swapped.
V
Optional right orthogonal matrix (N×N)
flags
Operation flags; can be 0 or combination of the following values:

The function cvSVD decomposes matrix A into a product of a diagonal matrix and two orthogonal matrices:

A=U*W*VT

Where W is diagonal matrix of singular values that can be coded as a 1D vector of singular values and U and V. All the singular values are non-negative and sorted (together with U and and V columns) in descenting order.

SVD algorithm is numerically robust and its typical applications include:


SVBkSb

Performs singular value back substitution

void  cvSVBkSb( const CvArr* W, const CvArr* U, const CvArr* V,
                const CvArr* B, CvArr* X, int flags );

W
Matrix or vector of singular values.
U
Left orthogonal matrix (tranposed, perhaps)
V
Right orthogonal matrix (tranposed, perhaps)
B
The matrix to multiply the pseudo-inverse of the original matrix A by. This is the optional parameter. If it is omitted then it is assumed to be an identity matrix of an appropriate size (So X will be the reconstructed pseudo-inverse of A).
X
The destination matrix: result of back substitution.
flags
Operation flags, should match exactly to the flags passed to cvSVD.

The function cvSVBkSb calculates back substitution for decomposed matrix A (see cvSVD description) and matrix B:

X=V*W-1*UT*B

Where

W-1(i,i)=1/W(i,i) if W(i,i) > epsilon•sumiW(i,i),
                    0        otherwise

And epsilon is a small number that depends on the matrix data type.

This function together with cvSVD is used inside cvInvert and cvSolve, and the possible reason to use these (svd & bksb) "low-level" function is to avoid temporary matrices allocation inside the high-level counterparts (inv & solve).


EigenVV

Computes eigenvalues and eigenvectors of symmetric matrix

void cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, double eps=0 );

mat
The input symmetric square matrix. It is modified during the processing.
evects
The output matrix of eigenvectors, stored as a subsequent rows.
evals
The output vector of eigenvalues, stored in the descenting order (order of eigenvalues and eigenvectors is syncronized, of course).
eps
Accuracy of diagonalization (typically, DBL_EPSILON=≈10-15 is enough).

The function cvEigenVV computes the eigenvalues and eigenvectors of the matrix A:

mat*evects(i,:)' = evals(i)*evects(i,:)' (in MATLAB notation)

The contents of matrix A is destroyed by the function.

Currently the function is slower than cvSVD yet less accurate, so if A is known to be positively-defined (for example, it is a covariation matrix), it is recommended to use cvSVD to find eigenvalues and eigenvectors of A, especially if eigenvectors are not required. That is, instead of

cvEigenVV(mat, eigenvals, eigenvects);
call
cvSVD(mat, eigenvals, eigenvects, 0, CV_SVD_U_T + CV_SVD_MODIFY_A);


CalcCovarMatrix

Calculates covariation matrix of the set of vectors

void cvCalcCovarMatrix( const CvArr** vects, int count, CvArr* cov_mat, CvArr* avg, int flags );

vects
The input vectors. They all must have the same type and the same size. The vectors do not have to be 1D, they can be 2D (e.g. images) etc.
count
The number of input vectors.
cov_mat
The output covariation matrix that should be floating-point and square.
avg
The input or output (depending on the flags) array - the mean (average) vector of the input vectors.
flags
The operation flags, a combination of the following values:
CV_COVAR_SCRAMBLED - the output covaration matrix is calculated as:
scale*[vects[0]-avg,vects[1]-avg,...]T*[vects[0]-avg,vects[1]-avg,...],
that is, the covariation matrix is count×count. Such an unusual covariation matrix is used for fast PCA of a set of very large vectors (see, for example, EigenFaces technique for face recognition). Eigenvalues of this "scrambled" matrix will match to the eigenvalues of the true covariation matrix and the "true" eigenvectors can be easily calculated from the eigenvectors of the "scrambled" covariation matrix.
CV_COVAR_NORMAL - the output covaration matrix is calculated as:
scale*[vects[0]-avg,vects[1]-avg,...]*[vects[0]-avg,vects[1]-avg,...]T,
that is, cov_mat will be a usual covariation matrix with the same linear size as the total number of elements in every 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 avg from the input vectors, but, instead, uses the passed avg vector. This is useful if avg has been already calculated somehow, or if the covariation matrix is calculated by parts - in this case, avg 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 covariation matrix is scaled by the number of input vectors. CV_COVAR_ROWS - Means that all the input vectors are stored as rows of a single matrix, vects[0]. count is ignored in this case, and avg should be a single-row vector of an appropriate size. CV_COVAR_COLS - Means that all the input vectors are stored as columns of a single matrix, vects[0]. count is ignored in this case, and avg should be a single-column vector of an appropriate size.

The function cvCalcCovarMatrix calculates the covariation matrix and, optionally, mean vector of the set of input vectors. The function can be used for PCA, for comparing vectors using Mahalanobis distance etc.


Mahalonobis

Calculates Mahalonobis distance between two vectors

double cvMahalanobis( const CvArr* vec1, const CvArr* vec2, CvArr* mat );

vec1
The first 1D source vector.
vec2
The second 1D source vector.
mat
The inverse covariation matrix.

The function cvMahalonobis calculates the weighted distance between two vectors and returns it:

d(vec1,vec2)=sqrt( sumi,j {mat(i,j)*(vec1(i)-vec2(i))*(vec1(j)-vec2(j))} )

The covariation matrix may be calculated using cvCalcCovarMatrix function and further inverted using cvInvert function (CV_SVD method is the preffered one, because the matrix might be singular).


CalcPCA

Performs Principal Component Analysis of a vector set

void cvCalcPCA( const CvArr* data, CvArr* avg,
                CvArr* eigenvalues, CvArr* eigenvectors, int flags );

data
The input data; each vector is either a single row (CV_PCA_DATA_AS_ROW) or a single column (CV_PCA_DATA_AS_COL).
avg
The mean (average) vector, computed inside the function or provided by user.
eigenvalues
The output eigenvalues of covariation matrix.
eigenvectors
The output eigenvectors of covariation matrix (i.e. principal components); one vector per row.
flags
The operation flags, a combination of the following values:
CV_PCA_DATA_AS_ROW - the vectors are stored as rows (i.e. all the components of a certain vector are stored continously)
CV_PCA_DATA_AS_COL - the vectors are stored as columns (i.e. values of a certain vector component are stored continuously)
(the above two flags are mutually exclusive)
CV_PCA_USE_AVG - use pre-computed average vector

The function cvCalcPCA performs PCA analysis of the vector set. First, it uses cvCalcCovarMatrix to compute covariation matrix and then it finds its eigenvalues and eigenvectors. The output number of eigenvalues/eigenvectors should be less than or equal to MIN(rows(data),cols(data)).


ProjectPCA

Projects vectors to the specified subspace

void cvProjectPCA( const CvArr* data, const CvArr* avg,
                   const CvArr* eigenvectors, CvArr* result )

data
The input data; each vector is either a single row or a single column.
avg
The mean (average) vector. If it is a single-row vector, it means that the input vectors are stored as rows of data; otherwise, it should be a single-column vector, then the vectors are stored as columns of data.
eigenvectors
The eigenvectors (principal components); one vector per row.
result
The output matrix of decomposition coefficients. The number of rows must be the same as the number of vectors, the number of columns must be less than or equal to the number of rows in eigenvectors. That it is less, the input vectors are projected into subspace of the first cols(result) principal components.

The function cvProjectPCA projects input vectors to the subspace represented by the orthonormal basis (eigenvectors). Before computing the dot products, avg vector is subtracted from the input vectors:

result(i,:)=(data(i,:)-avg)*eigenvectors' // for CV_PCA_DATA_AS_ROW layout.

BackProjectPCA

Reconstructs the original vectors from the projection coefficients

void cvBackProjectPCA( const CvArr* proj, const CvArr* avg,
                       const CvArr* eigenvects, CvArr* result );

proj
The input data; in the same format as result in cvProjectPCA.
avg
The mean (average) vector. If it is a single-row vector, it means that the output vectors are stored as rows of result; otherwise, it should be a single-column vector, then the vectors are stored as columns of result.
eigenvectors
The eigenvectors (principal components); one vector per row.
result
The output matrix of reconstructed vectors.

The function cvBackProjectPCA reconstructs the vectors from the projection coefficients:

result(i,:)=proj(i,:)*eigenvectors + avg // for CV_PCA_DATA_AS_ROW layout.

Math Functions


Round, Floor, Ceil

Converts floating-point number to integer

int cvRound( double value );
int cvFloor( double value );
int cvCeil( double value );

value
The input floating-point value

The functions cvRound, cvFloor and cvCeil convert input floating-point number to integer using one of the rounding modes. cvRound returns the nearest integer value to the argument. cvFloor returns the maximum integer value that is not larger than the argument. cvCeil returns the minimum integer value that is not smaller than the argument. On some architectures the functions work much faster than the standard cast operations in C. If absolute value of the argument is greater than 231, the result is not determined. Special values (±Inf, NaN) are not handled.


Sqrt

Calculates square root

float cvSqrt( float value );

value
The input floating-point value

The function cvSqrt calculates square root of the argument. If the argument is negative, the result is not determined.


InvSqrt

Calculates inverse square root

float cvInvSqrt( float value );

value
The input floating-point value

The function cvInvSqrt calculates inverse square root of the argument, and normally it is faster than 1./sqrt(value). If the argument is zero or negative, the result is not determined. Special values (±Inf, NaN) are not handled.


Cbrt

Calculates cubic root

float cvCbrt( float value );

value
The input floating-point value

The function cvCbrt calculates cubic root of the argument, and normally it is faster than pow(value,1./3). Besides, negative arguments are handled properly. Special values (±Inf, NaN) are not handled.


FastArctan

Calculates angle of 2D vector

float cvFastArctan( float y, float x );

x
x-coordinate of 2D vector
y
y-coordinate of 2D vector

The function cvFastArctan calculates full-range angle of input 2D vector. The angle is measured in degrees and varies from 0° to 360°. The accuracy is ~0.1°


IsNaN

Determines if the argument is Not A Number

int cvIsNaN( double value );

value
The input floating-point value

The function cvIsNaN returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 otherwise.


IsInf

Determines if the argument is Infinity

int cvIsInf( double value );

value
The input floating-point value

The function cvIsInf returns 1 if the argument is ±Infinity (as defined by IEEE754 standard), 0 otherwise.


CartToPolar

Calculates magnitude and/or angle of 2d vectors

void cvCartToPolar( const CvArr* x, const CvArr* y, CvArr* magnitude,
                    CvArr* angle=NULL, int angle_in_degrees=0 );

x
The array of x-coordinates
y
The array of y-coordinates
magnitude
The destination array of magnitudes, may be set to NULL if it is not needed
angle
The destination array of angles, may be set to NULL if it is not needed. The angles are measured in radians