简体   繁体   中英

How to allocate the elements of a matrix in c++ opencv?

I have always used the C API and am trying to convert a simple project to the C++ API to get a handle on it, but I can't seem to figure out how to allocate the elements of a matrix in C++. For example, I have the following array:

double rotation[] = { 0, 1, 0,
                     -1, 0, 0,
                      0, 0, 1 };

I have a 3x3 Mat, allocated with Mat *rotation_vector = new Mat(3,3, CV_64FC1);

In C, it would simply be cvInitMatHeader(rotation_vector, 3, 3, CV_64FC1, rotation); . How is this done in C++?

You should use some variant of the cv::Mat object.

For small matrices where the size is known and fixed , you can use the cv::Matx object:

cv::Matx33d rotation(  0.0, 1.0, 0.0,
                      -1.0, 0.0, 0.0,
                       0.0, 0.0, 1.0 );

For dynamically sized, arrays, you use the cv::Mat object

cv::Mat aBigMatrix( 53, 71, cv::CV_64FC1, cv::Scalar::all( 0.0 ) );

This would create a 2d-matrix with width of 53, height of 71, each element is a 64 bit floating point single-channel value ( basically a double ), and all of the elements will be set to 0.

Alternatively, you may use the cv::Mat_ template class, and the benefit is a cleaner initialization ( among other things ):

cv::Mat_<double> anotherBigMatrix( 53, 71, 0.0 );

This would create an equivalent matrix to the one described above.

Finally, you can use the template matrix class with an initialization list similar to the way you would do it in regular C:

There are many trade-offs to using the different classes, so you should make sure that you read the OpenCV documentation so that you pick the right one

If you just want to create a header for your already-allocated data, do:

cv::Mat rotation_matrix(3, 3, CV_64FC1, rotation)

this will make Mat a header for this data (no data will be copied). If you want to copy it to a new matrix, you can do:

cv::Mat new_matrix = rotation_matrix.clone();

You do not want to use new with cv::Mat (in almost all cases), it is a reference-counted datatype - think of it as a smart pointer. What was CvMat* should be cv::Mat (note the lack of a * ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM