Memory leak(opencv version 4.5.5)

Doing image similarity calculation. Start the application, each time the method is called, the memory used increases once, and cannot be released. After accumulating several times, the program fails due to insufficient memory. On win10, using System.gc(); can

public double CompareAndMarkDiff(Mat mat1, Mat mat2) {
        mat1 = Imgcodecs.imdecode(mat1, Imgcodecs.IMREAD_UNCHANGED);
        mat2 = Imgcodecs.imdecode(mat2, Imgcodecs.IMREAD_UNCHANGED);
        if (mat1.cols() == 0 || mat2.cols() == 0 || mat1.rows() == 0 || mat2.rows() == 0) {
            System.out.println("图片文件路径异常,获取的图片大小为0,无法读取");
            return 0;
        }
        if (mat1.cols() != mat2.cols() || mat1.rows() != mat2.rows()) {
            System.out.println("两张图片大小不同,无法比较,修正图片大小");
            int cols = Math.min(mat1.cols(), mat2.cols());
            int rows = Math.min(mat1.rows(), mat2.rows());
            Imgproc.resize(mat1, mat1, new Size(cols, rows), 0, 0, Imgproc.INTER_AREA);
            Imgproc.resize(mat2, mat2, new Size(cols, rows), 0, 0, Imgproc.INTER_AREA);
        }
        mat1.convertTo(mat1, CvType.CV_8UC1);
        mat2.convertTo(mat2, CvType.CV_8UC1);
        Mat mat1_gray = new Mat();
        Imgproc.cvtColor(mat1, mat1_gray, Imgproc.COLOR_BGR2GRAY);
        Mat mat2_gray = new Mat();
        Imgproc.cvtColor(mat2, mat2_gray, Imgproc.COLOR_BGR2GRAY);
        mat1_gray.convertTo(mat1_gray, CvType.CV_32F);
        mat2_gray.convertTo(mat2_gray, CvType.CV_32F);
        double result = Imgproc.compareHist(mat1_gray, mat2_gray, Imgproc.CV_COMP_CORREL);
        return result;
    }

temporarily solve it, but on linux, it still cannot be released. The problem is temporarily located at lines 2 and 3.

first, please post in english here, not in chinese, thank you.

then, opencv is a c++ library, it does not really allocate much memory on the java heap,
to free the c++ allocated memory, you need to release() all dynamically allocated Mat’s manually. in your function, this would be:

  • mat1, mat2 (from imdecode)
  • mat1_grey, mat2_grey (new)

then, compareHist() is for sure the wrong function to compare images directly,
it is for comparing image histograms , please take a close look !

p.s. none of those convertTo() calls make any sense

Thank you very much。