简体   繁体   中英

Image Processing in Android calling Garbage Collector

I am writing a custom grayscale conversion method:

public Mat grayScaleManual(Mat imageMat){
  Mat dst = new Mat(imageMat.width(), imageMat.height(), CvType.CV_8UC1);
  double[] bgrPixel;
  double grayscalePixel;

  for(int y = 0; y < imageMat.height(); y++){
      for(int x = 0; x < imageMat.width(); x++){
        bgrPixel = imageMat.get(y, x);
        grayscalePixel = (bgrPixel[0] + bgrPixel[1] + bgrPixel[2])/3;
        imageMat.put(y, x, grayscalePixel);
      }
  }

  return imageMat;
}

Mat is a class from the OpenCV4Android library. I know OpenCV has a built-in grayscaling method, but I want to make a comparison between my grayscale implementation and that of OpenCV.

This method always makes calls to the Garbage Collector. I know that the Garbage Collector is called when there are unused objects, but I do not think there are any unused objects in my code.

Why does this code keep calling the Garbage Collector?

The line

Mat dst = new Mat(imageMat.width(), imageMat.height(), CvType.CV_8UC1);

will allocate a new Mat object which will be discarded at the end of your method. This is probably the cause of your GCs in this method.

In the code you posted, dst is created and never accessed, nor is it returned by your function. When it goes out of scope at the end of the function, no references are left to dst , so the garbage collector is free to reclaim it.

To solve this, you can write the greyscale values to dst , and then return that instead. Otherwise, you are overwriting the image data inside imageMat with the greyscale pixels, but without changing the data type to CV_8UC1 . This will corrupt the data inside imageMat .

To fix this problem, call dst.put() instead of imageMat.put() , and return dst instead. The line:

imageMat.put(y, x, grayscalePixel);

then becomes:

dst.put(y, x, grayscalePixel);

I should also note that you are using a different formula for greyscale than OpenCV does. You are averaging RGB values to calculate grey value, while OpenCV uses the following formula (from the documentation ):

灰度方程

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM