我目前正在编写一个使用 EmguCV 拼接图像的程序。我使用 Emgu.CV.Stiching 类进行拼接算法,尽管我尝试正确处理资源,但我得到了巨大的内存泄漏,具体取决于我使用的图像的数量和大小。
这是我的代码的最小可复制示例
using System;
using System.IO;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.Stitching;
using Emgu.CV.Util;
using Emgu.CV.Features2D;
using Emgu.CV.CvEnum;
namespace Example
{
class Program
{
static void Main(string[] args)
{
string folderPath = @"e:\Users\Dennis\Desktop\Stitching\ExampleImages2"; //Paste your the path of your folder, which contains the images, here
string format = ".jpg";
string[] filePaths = Directory.GetFiles(folderPath, ("*" + format));
string storagePath;
Directory.CreateDirectory(folderPath + @"\Stitched"); //creates new Directionary if not exist
int num = 1; //Sets file numbering
while (true) //Checks if there is already an exisitng file with that name and change numbering "num" if "true"
{
storagePath = folderPath + @"\Stitched" + @"\result_" + num + format;
if (!File.Exists(storagePath))
break;
num++;
}
//Image Stitching
Stitcher.Mode mode = Stitcher.Mode.Scans;
float threshhold = 0.0001f;
Mat result = new Mat();
using (Stitcher stitcher = new Stitcher(mode)) //Creates a Stitcher configured with one of the stitching modes
using (AKAZE detector = new AKAZE(AKAZE.DescriptorType.Mldb, 0, 3, threshhold)) //Creates a Feature Detector with a user-chosen threshhold
using (VectorOfMat input = new VectorOfMat())
{
stitcher.SetFeaturesFinder(detector);
Mat[] images = new Mat[filePaths.Length];
for (int i = 0; i < filePaths.Length; i++)
{
images[i] = CvInvoke.Imread(filePaths[i], ImreadModes.AnyColor);
}
input.Push(images);
for (int i = 0; i < filePaths.Length; i++)
{
images[i].Dispose();
}
stitcher.Stitch(input, result);
}
using (Image<Bgr, Byte> resImage = result.ToImage<Bgr, Byte>())
{
resImage.Save(storagePath);
}
result.Dispose();
Console.ReadKey(); //I included this, so the program wont stop and you can see, how the memory consumption graph is not falling
}
}
}
我正在使用 VS 2015 和 EmguCV 版本 4.1.0.3420 并运行调试构建。
她是一个示例图像,因此您可以重现该问题:
只需将图像放入文件夹并将文件夹路径粘贴到预期的代码行中即可。您可以使用 NuGet 安装我在代码中使用的 EmguCV 版本。