OpenCV, Variation of the Laplacian (Java)

耗尽温柔 提交于 2019-12-05 12:04:20

The Laplacian transformation can be replaced by a kernel applied with the filter2D method. I have been running that same python example in a java program like this:

    Mat destination = new Mat();
    Mat matGray=new Mat();  
    Mat kernel = new Mat(3,3, CvType.CV_32F){
       {
          put(0,0,0);
          put(0,1,-1);
          put(0,2,0);

          put(1,0-1);
          put(1,1,4);
          put(1,2,-1);

          put(2,0,0);
          put(2,1,-1);
          put(2,2,0);
       }
    };        
    Imgproc.cvtColor(image, matGray, Imgproc.COLOR_BGR2GRAY);          
    Imgproc.filter2D(matGray, destination, -1, kernel); 
    MatOfDouble median = new MatOfDouble();
    MatOfDouble std= new MatOfDouble();        
    Core.meanStdDev(destination, median , std);

    Math.pow(std.get(0,0)[0],2);

Hope this helps your coding.

Note: The values I get from the Python and Java program are different and I still didn't figure out why. Anyway the java code runs well.

Found out why the values were not the same. Using the Imgproc.Laplacian method instead of Imgproc.filter2D produces exactly the same values in python and java.

The new code becomes:

Mat destination = new Mat();
Mat matGray=new Mat();  

Imgproc.cvtColor(image, matGray, Imgproc.COLOR_BGR2GRAY);          
Imgproc.Laplacian(matGray, destination, 3); 
MatOfDouble median = new MatOfDouble();
MatOfDouble std= new MatOfDouble();        
Core.meanStdDev(destination, median , std);

Math.pow(std.get(0,0)[0],2);

Much simpler and with same results as python.

I have not found any direct function to calculate the variance of an image in OpenCV. But I have found something to calculate the mean standard deviation. And from mathematics, the variance is just the square of the mean standard deviation.

This is how I calculate the mean standard deviation of an image

Mat im = Imgcodecs.imread("relative/path/to/file");
Imgproc.cvtColor(im, im, Imgproc.COLOR_BGR2GRAY);
MatOfDouble mu = new MatOfDouble(); // mean
MatOfDouble sigma = new MatOfDouble(); // standard deviation
Core.meanStdDev(d, mu, sigma);
double variance = Math.pow(mu.get(0,0)[0], 2);

I ran this on a some 37 JPGs I converted from RAW (each about 8MB) and it worked albeit slowly. I tried doing this for my 340 pictures and my laptop turned off. There should be ways to optimize this.

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