javac++opencvimage-processingglcm

How to convert C++ implementation of GLCM into Java?


I got the following snippet from GitHub to compute the gray level co-occurrence matrix (GLCM) through OpenCV:

float energy=0,contrast=0,homogenity=0,IDM=0,entropy=0,mean1=0;
int row=img.rows,col=img.cols;
Mat gl=Mat::zeros(256,256,CV_32FC1);

//creating glcm matrix with 256 levels,radius=1 and in the horizontal direction 
for(int i=0;i<row;i++)
   for(int j=0;j<col-1;j++)
       gl.at<float>(img.at<uchar>(i,j),img.at<uchar>(i,j+1))=gl.at<float>(img.at<uchar>(i,j),img.at<uchar>(i,j+1))+1;   

// normalizing glcm matrix for parameter determination
gl=gl+gl.t();            
gl=gl/sum(gl)[0];

The code above is in C++. I need to convert this into Java but I'm stuck in this line:

gl.at<float>(img.at<uchar>(i,j),img.at<uchar>(i,j+1))=gl.at<‌​float>(img.at<uchar>‌​(i,j),img.at<uchar>(‌​i,j+1))+1; 

Can someone help me out with this?


Solution

  • The calculation of a 256x256 symmetric gray level co-occurrence matrix of image img (of class Mat) corresponding to an offset "one pixel to the right" may be implemented in Java through OpenCV as follows:

    Mat gl = Mat.zeros(256, 256, CvType.CV_64F);
    Mat glt = gl.clone();
    
    for (int y = 0; y < img.rows(); y++) {
        for (int x = 0; x < img.cols()-1; x++) {
    
            int i = (int) img.get(y, x)[0];
            int j = (int) img.get(y, x + 1)[0];
    
            double[] count = gl.get(i, j);
            count[0]++;
            gl.put(i, j, count);
        }
    }
    
    Core.transpose(gl, glt);
    Core.add(gl, glt, gl);
    Scalar sum = Core.sumElems(gl);
    Core.divide(gl, sum, gl);
    

    There is a good bunch of publicly available libraries to compute GLCMs and extract Haralick features from them in Java, for example GLCM2, JFeatureLib, etc.