Opencv (2) -- Basic structures (2)

Source: Internet
Author: User
Mat

Opencv C ++ N-dimen1_dense array class

The classMatRepresents an N-dimenspondense numerical single-channel or multi-channel array.It can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel volumes, Vector Fields, point clouds, tensors, histograms (though, very high-dimen1_histograms may be better stored inSparsemat).

 

The data layout of the array is defined by the ArrayM. Step [], So that the address of element, where, is computed:

In case of a 2-dimen1_array, the above formula is already CED:

 

Note thatM. Step [I]> = M. Step [I + 1](In fact,M. Step [I]> = M. Step [I + 1] * M. Size [I + 1]). This means that 2-dimen1_matrices are stored row-by-row, 3-dimen1_matrices are stored plane-by-plane, and so on.M. Step [M. dims-1]Is minimal and always equal to the element sizeM. elemsize ().

 

There are too different ways to createMatObject.

UseCreate (nrows, ncols, type)Method or the similarMAT (nrows, ncols, type [, fillvalue])Constructor.

// make a 7x7 complex matrix filled with 1+3j.Mat M(7,7,CV_32FC2,Scalar(1,3));// and now turn M to a 100x60 15-channel 8-bit matrix.// The old content will be deallocatedM.create(100,60,CV_8UC(15));

As noted in the introduction to this chapter,Create ()Allocates only a new array when the shape or type of the current array are different from the specified ones.

Create a multi-dimen1_array:

// create a 100x100x100 8-bit arrayint sz[] = {100, 100, 100};Mat bigCube(3, sz, CV_8U, Scalar::all(0));

It passes the number of dimensions = 1 toMatConstructor but the created array will be 2-dimentor with the number of columns set to 1. So,MAT: dimsIs always> = 2 (can also be 0 when the array is empty ).

Construct a header for a part of another array. It can be a single row, single column, several rows, several columns, rectangular region in the array (calledMinorIn algebra) or a diagonal. Such operations are also O (1) because the new header references the same data. You can actually modify a part of the array using this feature, for example:

// add the 5-th row, multiplied by 3 to the 3rd rowM.row(3) = M.row(3) + M.row(5)*3;// now copy the 7-th column to the 1-st column// M.col(1) = M.col(7); // this will not workMat M1 = M.col(1);M.col(7).copyTo(M1);// create a new 320x240 imageMat img(Size(320,240),CV_8UC3);// select a ROIMat roi(img, Rect(10,10,100,100));// fill the ROI with (0,255,0) (which is green in RGB space);// the original 320x240 image will be modifiedroi = Scalar(0,255,0);

Due to the additionalDatastartAndDataendMembers, it is possible to compute a relative sub-array position in the mainContainerArray UsingLocateroi ():

Mat A = Mat::eye(10, 10, CV_32S);// extracts A columns, 1 (inclusive) to 3 (exclusive).Mat B = A(Range::all(), Range(1, 3));// extracts B rows, 5 (inclusive) to 9 (exclusive).// that is, C ~ A(Range(5, 9), Range(1, 3))Mat C = B(Range(5, 9), Range::all());Size size; Point ofs;C.locateROI(size, ofs);// size will be (width=10,height=10) and the ofs will be (x=1, y=5)

 

Make a header for user-allocated data. It can be useful to do the following:

Process "foreign" data using opencv (for example, when you implement a DirectShow * filter or a processing moduleGstreamer, And so on). For example:

void process_video_frame(const unsigned char* pixels,                         int width, int height, int step){    Mat img(height, width, CV_8UC3, pixels, step);    GaussianBlur(img, img, Size(7,7), 1.5, 1.5);}

Quickly initialize small matrices and/or get a super-fast element access.

double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}};Mat M = Mat(3, 3, CV_64F, m).inv();

 

Partial yet very common cases of thisUser-allocated dataCase are conversions fromCvmatAndIplimageToMat. For this purpose, there are special constructors taking pointersCvmatOrIplimageAnd the optional flag indicating whether to copy the data or not.

Backward conversion fromMatToCvmatOrIplimageIs provided via cast OperatorsMAT: Operator cvmat () constAndMAT: Operator iplimage (). The operators do not copy the data.

IplImage* img = cvLoadImage("greatwave.jpg", 1);Mat mtx(img); // convert IplImage* -> MatCvMat oldmat = mtx; // convert Mat -> CvMatCV_Assert(oldmat.cols == img->width && oldmat.rows == img->height &&    oldmat.data.ptr == (uchar*)img->imageData && oldmat.step == img->widthStep);

 

Use Matlab-style array initializers,Zeros (), ones (), eye (), For example:

// create a double-precision identity martix and add it to M.M += Mat::eye(M.rows, M.cols, CV_64F);

 

 

Use a comma-separated initializer:

// create a 3x3 double-precision identity matrixMat M = (Mat_<double>(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1);

 

// compute sum of positive matrix elements// (assuming that M isa double-precision matrix)double sum=0;for(int i = 0; i < M.rows; i++){    const double* Mi = M.ptr<double>(i);    for(int j = 0; j < M.cols; j++)        sum += std::max(Mi[j], 0.);}

 

// compute the sum of positive matrix elements, optimized variantdouble sum=0;int cols = M.cols, rows = M.rows;if(M.isContinuous()){    cols *= rows;    rows = 1;}for(int i = 0; i < rows; i++){    const double* Mi = M.ptr<double>(i);    for(int j = 0; j < cols; j++)        sum += std::max(Mi[j], 0.);}

 

// compute sum of positive matrix elements, iterator-based variantdouble sum=0;MatConstIterator_<double> it = M.begin<double>(), it_end = M.end<double>();for(; it != it_end; ++it)    sum += std::max(*it, 0.);

 

MAT: Row

Creates a matrix header for the specified matrix row.

The method makes a new header for the specified matrix row and returns it. this is an O (1) operation, regardless of the matrix size. the underlying data of the new matrix is shared with the original matrix.

MAT: rowrange

Creates a matrix header for the specified row span.

The method makes a new header for the specified row span of the matrix. SimilarlyMAT: Row ()AndMAT: COL (), This is an O (1) operation.

MAT: copyto

Copies the Matrix to another one.

The method copies the matrix data to another matrix. before copying the data, the method invokes

m.create(this->size(), this->type());

So that the destination matrix is reallocated if needed. WhileM. copyto (m );Works flawlessly, the function does not handle the case of a partial overlap between the source and the destination matrices.

When the operation mask is specified, ifMAT: CreateCall shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data.

 

  • MAT: assignto
  • MAT: setto
  • MAT: reshape
  • MAT: T
  • MAT: inv
  • MAT: MUL
  • MAT: Cross
  • MAT: dot
  • MAT: Zeros
  • MAT: ones
  • MAT: Eye
  • MAT: Create
  • MAT: addref
  • MAT: Release
  • MAT: resize
  • MAT: Reserve
  • MAT: push_back
  • MAT: pop_back
  • MAT: locateroi
  • MAT: adjustroi
  • MAT: Operator ()
  • MAT: Operator cvmat
  • MAT: Operator iplimage
  • MAT: Total
  • MAT: iscontinuous
  • MAT: elemsize
  • MAT: elemsize1
  • MAT: Type
  • MAT: Depth
  • MAT: Channels
  • MAT: Step 1
  • MAT: Size
  • MAT: empty
  • MAT: PTR
  • MAT:
  • MAT: Begin
  • MAT: End

 

The degree of familiarity with the mat Class determines the ability to manipulate opencv. It takes time to master it ~~

Opencv (2) -- Basic structures (2)

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.