Initialize the values into Mat object in OpenCV

Your question is not entirely clear to me, but I'm going to assume you are trying to load a float array into a OpenCV Mat object in a single row. First of all, be sure to check the documentation on constructing a Mat in C++. Since you have a 1D array and (I assume) you know the rows and columns you want to give your Mat, you should use this constructor:

cv::Mat::Mat (int rows, int cols, int type, void * data, size_t step = AUTO_STEP)   

Here's a code example:

float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cv::Mat your_matrix = cv::Mat(1, 10, CV_32F, data);

cout << your_matrix.at<float>(0,2) << endl;
cout << your_matrix << endl;

It will output:

3
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Of course you can change the datatype according to your needs (e.g. use int instead of float). You can ignore the AUTO_STEP parameter, but be sure to check the documentation on the usage if you want to use it. Also, if you want to change the structure of your Mat (e.g. split the array into multiple rows) you can achieve this by changing the rows and cols arguments in the constructor:

float data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
cv::Mat your_matrix = cv::Mat(2, 5, CV_32F, data);

cout << your_matrix.at<float>(1,2) << endl;
cout << your_matrix << endl;

It will output:

8
[1, 2, 3, 4, 5; 
6, 7, 8, 9, 10]

You have now split your Mat object into two rows of 5 columns, instead of 1 row of 10 columns.

In case of Java: If you want to do this in Java, you were already on the right track. However, you probably forgot to specify the rows, columns and channels/depth. Change the rows, cols and CvType according to whatever suits your data as before. You can do the following:

float data[] = new float[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Mat mat = new Mat(1, 10, CvType.CV_32F);
mat.put(0, 0, data);

Be sure to check the Java documentation on Mat as well!


Try inline initialization if you want to hardcode those values.:

    // For small matrices you may use comma separated initializers:

    Mat C = (Mat_<double>(3,3) << 0, -1, 0, -1, 5, -1, 0, -1, 0);
    cout << "C = " << endl << " " << C << endl << endl;

stolen from

http://opencvexamples.blogspot.de/2013/09/creating-matrix-in-different-ways.html?m=1

use data array as source as shown in some else's answer if you want to use a (maybe dynamic) array as input.

Tags:

Java

Opencv

Mat