Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/230.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Android调用垃圾收集器中的图像处理_Java_Android_Opencv_Image Processing_Garbage Collection - Fatal编程技术网

Java Android调用垃圾收集器中的图像处理

Java Android调用垃圾收集器中的图像处理,java,android,opencv,image-processing,garbage-collection,Java,Android,Opencv,Image Processing,Garbage Collection,我正在编写一种自定义灰度转换方法: 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;

我正在编写一种自定义灰度转换方法:

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;
}
public Mat grayscalemanal(Mat imageMat){
Mat dst=新的Mat(imageMat.width()、imageMat.height()、CvType.CV_8UC1);
双[]bgrPixel;
双灰度像素;
对于(int y=0;y
Mat
是OpenCV4Android库中的一个类。我知道OpenCV有一个内置的灰度缩放方法,但我想比较一下我的灰度实现和OpenCV的灰度实现

此方法始终调用垃圾收集器。我知道当存在未使用的对象时会调用垃圾收集器,但我认为我的代码中没有任何未使用的对象

为什么这段代码一直在调用垃圾收集器?

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

将分配一个新的Mat对象,该对象将在方法结束时丢弃。这可能是您使用此方法的GCs的原因。

在您发布的代码中,
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使用以下公式(来自):