OpenCV How to initialize Mat with a 2D array in JAVA

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

+3
source share
5 answers

Sorry, I do not know about Java, but I can offer general logic. In C ++ openCV, we do this on 2 for loopsas follows:

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 this was your request.

+2
source

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

The code itself explains: you have data in the TrainingData array, and you assign a new Mat object. Then you use the put method to push the lines in place.

+4
source

matObject , , Mat? , :

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

inputImage matObject?

0
source

Usage can use put method for Mat for this. The 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]);
}
0
source

use

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

All Articles