Opencv2: mat

Source: Internet
Author: User
Tags scalar
1. The mat is based on the computer memory. Digital Images are stored in a matrix. In opencv2, the data structure mat is a matrix that stores image pixel information. It consists of two parts: a matrix header and a matrix pointer pointing to pixel data. The matrix header mainly includes the matrix size, storage method, storage address, and reference count. The size of the matrix header is a constant that does not change with the size of the image. However, the size of the matrix that stores the pixel data of the image changes with the size of the image. Generally, the amount of data is large, it is several orders of magnitude larger than the matrix header. In this way, in the process of image copying and transmission, the main overhead is caused by storing the matrix of image pixels. Therefore, opencv uses the number of references. When copying and transferring images, it does not copy the entire mat data, but just copies the matrix header and pointer to the pixel matrix. For example:
CV: mat a; // create the matrix header A = CV: imread ("F: \ psb.jpg"); // read the image CV: mat B =; // copy
The preceding A and B have their own matrix headers, but the matrix Pointer Points to the same matrix, that is, any change to the matrix data will affect the other. So who will release the matrix data when multiple mat nodes share the same matrix data? This is the function of reference count. When the mat object is copied once, it will add 1 to the reference count, and each time a mat object is destroyed (sharing the same matrix data) the reference count is reduced by 1. When the reference count is 0, the matrix data is cleared. Because Mat object A and B share a matrix, the reference count refcount is 2. but sometimes we still need to copy the matrix data itself (not just the matrix header and the matrix pointer). In this case, we can use the clone and copyto methods.
cv::Mat c = a.clone();cv::Mat d ;a.copyTo(d);
In the above Code, c and d have their own matrices, and changing their matrix data will not affect each other. When using mat, remember:
  1. The memory allocation in opencv is automatically completed (not specifically specified)
  2. When using the C ++ interface of opencv, you do not need to consider the memory release issue.
  3. The assignment operation and copy constructor of mat only copy the matrix header and still share the same matrix.
  4. To copy matrix data, you can use the clone and copyto functions.
2. mat storage method in mat, each element of the matrix can use different data types. The smallest data type is Char, which occupies one byte or eight digits and can be signed (0 to 255) or unsigned (-127 to 127 ). In the RGB color space, three char types can be used to represent the color of 16 million, but float or double may be used to represent the pixels of the image during image processing. Create a constructor for mat
cv::Mat img(2,2,CV_8UC3,cv::Scalar(0,0,255));
The above Code creates a matrix with two rows and two columns. The matrix elements are saved in 8-bit unsigned char type and have three channels. The initial values of each pixel are (255)
The first two parameters of the constructor specify the rows and columns of the matrix.
The third parameter specifies the data type and number of channels of the matrix element. The rules are as follows:
CV_[The number of bits per item][Signed or Unsigned][TypePrefix]C[The channel number]
The four parts respectively specify the size of the element, whether it is signed or unsigned, the data type and the last parameter of the number of channels. scalar is a short-type vector that provides matrix initialization. Create method this method cannot set an initial value for the matrix, but only re-allocates memory for the matrix data when the size is changed. Usage:
img.create(4,4,CV_8UC(2));
Creates a 4-row, 4-column, and 2-Channel Matrix Matlab-form initialization.
cv::Mat e = cv::Mat::eye(4,4,CV_64F);cv::Mat z = cv::Mat::ones(2,2,CV_32F);cv::Mat o = cv::Mat::zeros(3,3,CV_8UC1);
Mat e is the diagonal matrix of four rows and four columns. Mat Z is the unit matrix of two rows and two columns. Mat o is the zero matrix of three rows and three columns. initialization of the small matrix can be separated by commas. initialization Function
Mat c =(Mat_<double>(3,3)<<1,2,3,0,-1,0,4,5,6);
It is convenient to define a template when performing template operations on images. 3. the input and output of Mat use the imread function to write an image to the mat object.
A = CV: imread ("F: \ psb.jpg"); // read the image
The imread prototype is as follows:
cv::Mat imread(const string& filename,int flags=1)
Filename specifies the position of the image to be read. Flags specifies the color space of the image. Flags> 0 3-channel color image. Flags = 0 grayscale image. Flags <0 is not changed.
You can also have the following enumerated values: cv_load_image_anydepth, cv_load_image_color, and cv_load_image_grayscale.
Use the imwrite function to save the mat object to the specified file. The imwrite function prototype is as follows:
bool imwrite(const string& filename,InputArray img,constvector<int>& params=vector<int>())
Filename: Specifies the mat object Params to be saved by the specified object IMG to specify the storage encoding method of the image. Use the extension name of filenameto specify the image format (.jpg. PNG. BMP). For different Image Storage types, Params are different values.
  • JPEG and Params are used to specify the image quality (0 to 100). The default value is 95. cv_imwrite_jpeg_quality.
  • PNG and Params are used to specify the compression level (0 to 9) of the image. The higher the compression level, the smaller the space occupied by the image. The longer the image is saved. The default value is 3. cv_imwrite_png_compression.
  • PPM, PGM, PBM, and Params are a tag (0 or 1). The default value is 1. cv_imwrite_pxm_binary.
Imwrite can only store 8-bit (or 16-bit unsigned (cv_16uc) PNG, or tiff images) single-channel or three-channel images. If you want to save images that are not like this, you can use convertor or cvtcolor for transformation. The following code shows how to use imwrite to write a 4-channel PNG image to a file.
void createAlphaMat(Mat &mat) {    for(int i = 0 ; i < mat.rows ; i ++) {        for(int j = 0 ; j < mat.cols ; j ++) {            Vec4b &rgba = mat.at<Vec4b>(i,j);            rgba[0] = UCHAR_MAX ;            rgba[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX);            rgba[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX);            rgba[3] = saturate_cast<uchar>(0.5 * (rgba[1] + rgba[2]));        }    }}int main(){    Mat mat(480,640,CV_8UC4);    createAlphaMat(mat);    vector<int> compression_params ;    compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);    compression_params.push_back(9);    imwrite("alpha.png",mat,compression_params);    return 0;}

 

4. Mat display opencv provides a method to display images in a window. The Code is as follows:
Mat img = imread("f:\psb.jpg");const string name ="Hu";namedWindow(name);imshow(name,img);waitKey();

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.