Even just doing the most basic video streaming causes a memory leak for me.
cvNamedWindow("1",0);
CvCapture *fc = cvCaptureFromCAM(0);
IplImage *frame = NULL;
CvSize frameSize;
frameSize.height = cvGetCaptureProperty(fc, CV_CAP_PROP_FRAME_HEIGHT);
frameSize.width = cvGetCaptureProperty(fc, CV_CAP_PROP_FRAME_WIDTH);
while (1) {
IplImage *wrkImage = NULL;
frame = cvQueryFrame(fc);
if (!frame)
break;
wrkImage = cvCreateImage(frameSize, IPL_DEPTH_8U, 3);
cvCopy(frame, wrkImage, NULL);
cvShowImage("1", wrkImage);
char c = cvWaitKey(33);
if (c == 27) {
break;
}
cvReleaseImage(&wrkImage);
}
Apparently according to the book “Learning OpenCV”, I’m not supposed to release “frame” since it’s managed by openCV and I can “expect problems if I do”. It does indeed cause problems if I release the frame pointer once I’ve called cvQueryFrame. The book also suggests copying the image pointed to by cvQueryFrame elsewhere to work on it since cvQueryFrame presumably recycles the same chunk of memory repeatedly. Hence wrkImage which I do release at the end of each frame cycle. The program crashes after a few mins, and leaks memory like crazy! Leads me to believe something major is getting leaked like entire frames. I’m wondering if anyone uses OpenCV 2.1 on the Mac for video stuff and has found this to be an issue as well. Or if anyone can see a gaping hole in my code that I’m missing.
Any advice from OpenCV guru’s out there would be much appreciated!
Edit: After carefully stepping through the program and examining memory, I suspect the issue is with cvShowImage(). cvShowImage seems to allocate about a frame’s worth of memory that never seems to get reclaimed. Then found this link OpenCV cvShowImage Memory Leaks OSX that seems to agree with my suspicions. Might be close to a solution here… Just glad to see I’m not crazy!
UPDATE: The Macports OpenCV is fine now (and has been for a few months now. Just thought I should post that here so people aren’t getting discouraged from using macports for their OpenCV build/install. Macports is a great way to install OpenCV.
There is nothing wrong with the code I provided. The current MacPorts build of openCV has a memory leak in the cvShowImage() function. I downloaded and built the most recent version manually, and it no longer leaks memory.
For anyone who reads this, if your openCV program is curiously leaking memory, and you installed using MacPorts, I’d suggest downloading the source and building manually using cmake.