OpenCV How to initialize Mat with 2D array in JAVA

Rabbir picture Rabbir · Feb 16, 2014 · Viewed 11.3k times · Source

Suppose, I have a 2D array initialized with values, how do I put this value in a Mat object in OpenCV?

Answer

radhoo picture radhoo · May 5, 2014

probably something like this will work:

float trainingData[][] = new float[][]{ new float[]{501, 10}, new float[]{255, 10}, new float[]{501, 255}, new float[]{10, 501} };
Mat trainingDataMat = new Mat(4, 2, CvType.CV_32FC1);//HxW 4x2
for (int i=0;i<4;i++)
        trainingDataMat.put(i,0, trainingData[i]);

Code is self explanatory: you have the data in the "TrainingData" array, and you allocate the new Mat object. Then you use the "put" method to push the rows in place.