OpenCV How to initialize Mat with 2D array in JAVA

感情迁移 提交于 2019-12-22 08:57:39

问题


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


回答1:


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:


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.




回答3:


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?




回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/21812490/opencv-how-to-initialize-mat-with-2d-array-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!