Suppose, I have a 2D array initialized with values, how do I put this value in a Mat object in OpenCV?
5 Answers
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.
Comments
Sorry don't know about Java but can suggest the general logic. In C++ openCV we do it by 2 for loops as following:
matObject.create( array.rows, array.cols, CV_8UC1 ); // 8-bit single channel image
for (int i=0; i<array.rows; i++)
{
for(int j=0; j<array.cols; j++)
{
matObject.at<uchar>(i,j) = array[i][j];
}
}
Let me know if it was your query..
2 Comments
Rabbir
What is the alternative for matObject.at<uchar>(i,j) = array[i][j]; in JAVA? I can't find anything.
skm
sorry i don't know about java...but it is just a method to access the pixel at location (i,j) and this is the basic thing in image processing so should be very very easy. In
matObject.at<uchar>(i,j) = array[i][j];, we are just accessing the image's pixel at (i,j) and putting a value at that location. PS: Do not forget to do the proper typecast. If the values stored in array are of integer type then matObject.at<uchar>(i,j) = (uchar)array[i][j];use to
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
Mat array= Highgui.imread("java.png" ,CvType.CV_8UC1 );
Mat matObject = new Mat();
matObject.create( array.rows(), array.cols(),CvType.CV_8UC1 );
for (int i=0; i<array.rows(); i++)
{
for(int j=0; j<array.cols(); j++)
{
matObject.put(i, j, array.get(i, j));
}
}
Highgui.imwrite("java2.jpg", matObject);