javaopencvmat

Initialize the values into Mat object in OpenCV


I need to initialize these array values directly into a Mat object. I tried using obj.put(i,j,data) but this does not work and the Mat object is still empty. i need this in java

data [] = {103547.0, 2.0959531E7, 5.152769223E9, 1.415924406121E12, 2.0842905E7, 
           4.195143491E9, 1.025510364741E12, 5.000561607E9, 9.99289545049E11, 
           1.332451366923E12}

Can explain to me me how to initialize a new Mat object where I directly insert the array data?


Solution

  • 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!