4

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

0

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

What is the alternative for matObject.at<uchar>(i,j) = array[i][j]; in JAVA? I can't find anything.
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];
0

Is matObject a keyword or it means we have to substitute with the name of the Mat image? For example if I have defined an image as:

Mat inputImage = imread ("C:\Documents and Settings\user\My Documents\My Pictures\Images\imageName.jpg");

then should I put inputImage instead of matObject?

Comments

0

Use can use put method of Mat for this. Code

int[][] intArray = new int[][]{{2,3,4},{5,6,7},{8,9,10}};
Mat matObject = new Mat(3,3,CvType.CV_8UC1);
for(int row=0;row<3;row++){
   for(int col=0;col<3;col++)
        matObject.put(row, col, intArray[row][col]);
}

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.