How to avoid the OpenCV out of memory exception?
I am using OpenCvSharp and this code to get the position of a user's eyes.
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;
}
}
}
}
It works, but the program gets bigger and bigger in memory till it finally says that it doesn't have enough and points at
CvSeq<CvAvgComp> eyes = Cv.HaarDetectObjects(smallImg, cascade, storage, ScaleFactor, MinNeighbors, 0, new CvSize(30, 30));
How to solve this out of memory exception?
I'm not familiar with OpenCVSharp. But normally the
IplImage
structure is outdated and replaced by theMat
structure (IplImage
is OpenCV 1 structure).If the
Mat
structure exists in OpenCVSharp I highly recommend you to use it. With theIplImage
structure you have to free the memory manually. I think yourIplImage img
,IplImage smallImg
andIplImage gray
will be allocated each loop continous new, but is not freed after use.also please do not re-load the haar-cascade for each frame processed, but only once (on startup of your prog)
@matman How do you use the Mat structure? I tried CvMat img = cap.QueryFrame();
@berak That solved it. Great!
@PeterWeter, again, like matman said before, - also prefer the Mat interfaces instead of the outdated IplImage ones.
In C++ it is not
CvMat
, butcv::Mat
. Cv"Something" suggests that it is still the old C structure.berak gave the solution - only load cascade once and reuse it. Please close question as solved. -Edit - oh question is from 2015 - Greetings from the future.