0

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?

4

2 回答 2

0

在您发布的代码中,dst它被创建并且从未被访问过,也不会由您的函数返回。当它在函数结束时超出范围时,不会留下对 的引用dst,因此垃圾收集器可以自由地回收它。

要解决此问题,您可以将灰度值写入dst,然后将其返回。否则,您将imageMat使用灰度像素覆盖内部的图像数据,但不会将数据类型更改为CV_8UC1. 这会破坏里面的数据imageMat

要解决此问题,请调用dst.put()而不是imageMat.put(),然后返回dst。该行:

imageMat.put(y, x, grayscalePixel);

然后变成:

dst.put(y, x, grayscalePixel);

我还应该注意,您使用的灰度公式与 OpenCV 不同。您正在平均 RGB 值来计算灰度值,而 OpenCV 使用以下公式(来自文档):

灰度方程

于 2013-07-07T20:26:29.633 回答
0

线

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

将分配一个新的 Mat 对象,该对象将在您的方法结束时被丢弃。这可能是您在此方法中出现 GC 的原因。

于 2013-07-07T05:12:40.660 回答