I have recently been doing some circle detection in OpenCV and I have had some great success. The code below works wonderfully in C++ on a 32-bit platform. I do however have one small problem; as the program runs my RAM loads continues to load up. For example, when I start the program I am at 250mb, 30 seconds later I am at about 800mb. This continues and eventually overflows to the hard drive. I have tried to move the cvReleaseCapture inside the while loop but I just get the old “Exception at memory location….”. Any ideas how I can clean this up? Thanks a lot. Here’s the code:
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <math.h>
int main( int argc, char **argv )
{
CvCapture *capture = 0;
IplImage *img = 0;
int key = 0;
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_PLAIN,1.0,1.0,0,1,CV_AA);
capture = cvCaptureFromCAM( 0 );
if ( !capture ) {
fprintf( stderr, "Cannot open initialize webcam!\n" );
return 1;
}
cvNamedWindow( "result", CV_WINDOW_AUTOSIZE );
while( key != 'q' ) {
img = cvQueryFrame( capture );
IplImage* gray = cvCreateImage( cvGetSize(img), 8, 1 );
CvMemStorage* storage = cvCreateMemStorage(0);
cvCvtColor( img, gray, CV_BGR2GRAY );
cvSmooth( gray, gray, CV_GAUSSIAN, 9, 9 );
CvSeq* circles = cvHoughCircles( gray, storage, CV_HOUGH_GRADIENT, 2, gray- >height/4, 200, 100, 20, 100 );
int i;
for( i = 0; i < circles->total; i++ )
{
float* p = (float*)cvGetSeqElem( circles, i );
//cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 2, CV_RGB(0,255,0), -1, 8, 0 );
cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(0,255,0), 2, 8, 0 );
cvLine (img, cvPoint(cvRound(p[0]+40),cvRound(p[1])), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
cvLine (img, cvPoint(cvRound(p[0]),cvRound(p[1]+40)), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
cvLine (img, cvPoint(cvRound(p[0]-40),cvRound(p[1])), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
cvLine (img, cvPoint(cvRound(p[0]),cvRound(p[1]-40)), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
cvPutText(img, "Meow",cvPoint(cvRound(p[0]+45),cvRound(p[1]+45)), &font, CV_RGB(0,0,255));
}
if( !img ) break;
cvShowImage( "result", img );
key = cvWaitKey( 1 );
cvReleaseCapture( &capture );
}
cvDestroyWindow( "result" );
cvReleaseCapture( &capture );
return 0;
}
Get rid of the
cvReleaseCaptureinside the while loop. Instead, you should haveAnd you should probably move the
if (!img) break;line up so it reads:Edit
Actually, instead of constantly creating and then destroying
gray, you should do an initial capture (img = cvQueryFrame(capture);) outsid eof thewhileloop. Then creategrayin the normal way. Then you don’t have to keep creating it in thewhileloop, which is why you’re running out of memory (you’re creating an new image every iteration without releasing it).So