OpenCV in The Matrix class: Mat

Source: Internet
Author: User
Tags scalar shallow copy
reproduced from: http://www.xuebuyuan.com/2148247.html
OpenCV One of the matrix classes: Mat
Summary

The mat class can be viewed as a matrix class in the C + + version of OpenCV, replacing the original C-version matrix structure Cvmat and the image structure iplimage;

Mat's biggest advantage with STL compatibility is very good, there are many similar to STL operation. But Mat is far stronger than the latter;

Mat is an efficient data type that dynamically manages memory and does not require the user to manually manage memory.

Mat class Definition

The Mat class is defined in CORE.HPP, which consists mainly of two parts of data: The matrix header, which is fixed, contains the size of the matrix, the way it is stored, the address of the Matrix store, and so on. ; another is a pointer to a matrix containing pixel values (data). The Mat class is defined as follows:

Class Cv_exports Mat
{public
:
    //... a lot of methods ...
    ...

    /*! Includes several bit-fields:
         -The Magic signature-continuity flag-depth-number of
         channels
     */< C10/>int flags;
    //! The array dimensionality, >= 2
    int dims;
    //! The number of rows and columns or ( -1,-1) when the array has more than 2 dimensions
    int rows, cols;
    //! Pointer to the data
    uchar* data;

    //! Pointer to the reference counter;
    When array points to user-allocated data, the pointer is NULL
    int* refcount;

    Other members
    ...
};

Mat Data Type

Mat storage is stored line by row, the data types in the matrix include:mat_<uchar> corresponding to the cv_8u,mat_<uchar> corresponding to the cv_8u,mat_<char> corresponding is Cv_8s,mat_ <int> corresponds to the cv_32s,mat_<float> corresponds to the cv_32f,mat_<double> corresponding is cv_64f, the corresponding data depth is as follows:

cv_8u-8-bit unsigned integers (0..255)

cv_8s-8-bit signed integers ( -128..127)

cv_16u-16-bit unsigned integers (0..65535)

cv_16s-16-bit signed integers ( -32768..32767)

cv_32s-32-bit signed integers ( -2147483648..2147483647)

cv_32f-32-bitfloating-point Numbers (-flt_max. Flt_max, INF, NAN)

cv_64f-64-bitfloating-point Numbers (-dbl_max. Dbl_max, INF, NAN) Create Mat Matrix

1. Using constructors, the common several are as follows: Mat::mat ();
Default Mat::mat (int rows, int cols, int type);
Mat::mat (size size, int type);
Mat::mat (int rows, int cols, int type, const scalar& s);
Mat::mat (size size, int type, const scalar& s);
Mat::mat (const mat& m); //int rows: High//int cols: Wide//int type: see "Mat type definition"//size size: Matrix size, note width and height order: size (cols, rows)//const scalar& s: The value used to initialize the matrix element//const mat& m: Copy M's matrix header to the new Mat object, but does not copy the data.
Equivalent to creating a reference object of M//Example 1: Create the 100*90 matrix, The matrix element is 3 channel 32-bit floating-point type Cv::mat M (A, CV_32FC3);
Example 2: Use one-dimensional or multidimensional arrays to initialize matrices, double m[3][3] = {{A, B, C}, {D, E, F}, {g, H, i}};

Cv::mat m = Cv::mat (3, 3, cv_64f, M);	2. Use CREATE function: Mat a = Create (9, cv_16u); Creates a 10*9 matrix that is a special use of a 16-bit unsigned integer//create: If you initialize a parameter that does not pass in the size, or you need to change the parameter of size later, you can use create to adjust//make 7x7 complex
Matrix filled with 1+3j.
Cv::mat M (7,7,cv_32fc2,scalar (1,3));
And now turn M to 100x60 15-channel 8-bit matrix. The old content would be deallocated: the implicit use of release () releases M.create (100,60,cv_8uc (15));
merging matrices
It is assumed that the existing matrix of n Cvmat types (each 1*m row vector) is merged into a matrix of n*m (n rows m columns), that is, the matrix merging problem.
cvmat* vector;//row vectors: 1*m
Mat DST;	Target matrix: n*m
Mat vectormat = Mat (vector, true);	Convert Cvmat to Mat
Mat Tmpmat = M.row (i);	Note: Shallow copy (see "Copy Matrix")
Vectormat.copyto (Tmpmat);	Note: Deep copy (at this time Tmpmat has been changed to Vectormat, that is, the i+1 row of the target matrix is assigned to Vectormat)
//above to change the value of the i+1 row of the target matrix, and so on, and so on, you can merge n row vectors into the target matrix.

Accessing matrix elements

1.at function
m.at<double> (i,j) + = 1.F;	Set (i,j)-th element
int a = m.at<int> (i,j);		Get (I,j)-th element
//2. Matrix elements Pointer (PTR) for
(int i = 0; i < m.rows; i++)
{
    const double* pData = m.pt R<double> (i);	All elements of line i+1 for
    (int j = 0; J < M.cols; J + +)
		cout<<pdata[j]<<endl;
}
A detailed explanation of Mat class member functions

Mat::eye

Returns an identity-specified size and type matrix.

C + +: static matexpr mat::eye (int rows, int cols, inttype)

C + +: Static matexpr mat::eye (size size, int type)

Parameters

Rows – the number of lines.

cols– The number of columns.

Size – A method that replaces the matrix size specification size (cols, rows).

type – the kind of matrix that is created.

This method returns the Matlab-type identity matrix initializer, similar to Mat::zeros () and Mat::ones (), which you can use to efficiently create the scaled identity matrix:

//Create a diagonal matrix of 4 x 4 and narrow diagonally by 0.1.

Mat A = Mat::eye (4, 4, cv_32f) *0.1; mat::create

Allocates new array data, if required.

C + +: void mat::create (int rows, int cols, int type)

C + +: void mat::create (size size, int type)

C + +: void mat::create (int ndims, const int* sizes, inttype)

Parameters

Ndims – The number of dimensions of the new array.

Rows – The new number of rows.

cols – The number of new columns.

Size – replaces the new matrix sizes Specification: Size (cols, rows).

Sizes – Specifies an array of integers for a new array shape.

type – the kind of the new matrix.

This is one of the key mat methods. Most new styles OpenCV functions and methods that produce arrays call this method for each output array. This method uses the following algorithm:

1. If the current array shape and type match new please return immediately. Otherwise, the previous data is dereference by calling Mat::release ().

2. Initialize the new matrix header.

3. Allocate new Total () *elemsize () bytes of data space.

4. Assign a reference count of the new associated data and set it to 1.

This program enables memory management to be powerful and efficient while also reducing additional input for users. This means that there is usually no need to explicitly allocate an output array. In other words, you can not write:

Mat color;

...

Mat Gray (Color.rows, color.cols,color.depth ());

Cvtcolor (color, gray, Cv_bgr2gray);

and write:

Mat color;

...

Mat Gray;

Cvtcolor (color, gray, Cv_bgr2gray);

Because Cvtcolor, like most OpenCV functions, calls Mat::create () internally when an array is output. Mat::addref

Counter Reference.

C + +: void Mat::addref ()

This method increments the reference count associated with the matrix data. If the matrix header points to an external dataset (see Mat::mat ()), the reference count is NULL, and the method does not work in this case. In general, you should not explicitly call the method to avoid a memory leak. It is called by the Fu Yin of the matrix assignment operation. On the supported platform, the reference counter increment is an atomic operation. Therefore, for the same matrix, asynchronous operations on different threads are safe. Mat::release

If necessary, decrements the reference count and releases the matrix.

C + +: void Mat::release ()

This method decrements the reference count associated with the data in the matrix. When the reference count is reduced to 0 o'clock, the data for the matrix is freed, and the data and reference counter pointers are set to NULL. If the matrix header points to an external dataset (see Mat::mat ()), the reference count is NULL, and the method is not valid in this case.

This method can be called manually to force the release of the matrix data. However, because this method is called automatically in a destructor, or to change other methods of the data pointer, this function is generally not required. On the platform that supports it, the reference counter decrements and checks whether 0 is an atomic operation. Therefore, it is a safe operation to call the same matrix asynchronously on different threads. mat::resize

Change the number of rows for the matrix.

C + +: void Mat::resize (size_t sz)

C + +: void Mat::resize (size_t sz, const scalar& s)

Parameters

SZ – The new number of rows.

s – The value that is assigned to the newly added element.

This method changes the number of rows in the matrix. If the matrix is redistributed, the first minimum (MAT::ROWS,SZ) number of rows should be retained. This method simulates the corresponding STL vector class method. Mat::reserve

A space that retains a certain number of rows.

C + +: void Mat::reserve (size_t sz)

Parameters

SZ – The number of rows.

The method sz row storage space. If the matrix already has enough space to store the SZ row, no exception occurs. If the matrix is reassigned, reserve the Front (mat::rows) row. This method simulates the corresponding STL vector class method. Mat::p ush_back

Adds an element to the bottom of the matrix.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.