如何避免OpenCV内存异常?

时间:2015-03-28 17:23:32

标签: c# opencv opencvsharp

我正在使用OpenCvSharp和此代码来获取用户眼睛的位置。

CvCapture cap = CvCapture.FromCamera(CaptureDevice.Any);
using (CvWindow w = new CvWindow("Eye Tracker"))
{

    while (CvWindow.WaitKey(10) < 0 && beginn) //beginn)
    {
        using (IplImage img = cap.QueryFrame())
        using (IplImage smallImg = new IplImage(new CvSize(Cv.Round(img.Width / Scale), Cv.Round(img.Height / Scale)), BitDepth.U8, 1))
        {

            using (IplImage gray = new IplImage(img.Size, BitDepth.U8, 1))
            {
                Cv.CvtColor(img, gray, ColorConversion.BgrToGray);
                Cv.Resize(gray, smallImg, Interpolation.Linear);
                Cv.EqualizeHist(smallImg, smallImg);
            }

            using (CvHaarClassifierCascade cascade = CvHaarClassifierCascade.FromFile(@"D:\haarcascade_eye.xml"))
            using (CvMemStorage storage = new CvMemStorage())
            {
                storage.Clear();
                CvSeq<CvAvgComp> eyes = Cv.HaarDetectObjects(smallImg, cascade, storage, ScaleFactor, MinNeighbors, 0, new CvSize(30, 30));
                if (eyes.Total == 2)
                {

                    // do something
                }
                w.Image = img;
            }
        }
    }
}

它有效,但程序在内存中变得越来越大,直到它最终说它没有足够的内容并指向

CvSeq<CvAvgComp> eyes = Cv.HaarDetectObjects(smallImg, cascade, storage, ScaleFactor, MinNeighbors, 0, new CvSize(30, 30));

如何解决这种内存不足的异常?

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,当我遇到你的帖子时正在寻找解决方案。经过我自己的挖掘后,我发现了那个叫

的东西
GC.Collect()
在循环结束时

将释放OpenCVSharp摄像头捕获所消耗的内存。即使你已经解决了你的问题,也许这将有助于其他一些在谷歌搜索中偶然发现的可怜的灵魂。