I would like to know how to find a memory leak since I am making a program which has one that I want to solve, the memory used increases very quickly and I need to solve the problem.
The program I am working on is face detection from webcam by OpenCv using the Javacv 1.1 and JavaCPP libraries.
private IplImage detectFace(IplImage image, CvScalar color) {
int number = 3;
IplImage imageGray = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
cvCvtColor(image, imageGray, CV_BGR2GRAY);
IplImage smallImg = IplImage.create(imageGray.width()/2, imageGray.height()/2, IPL_DEPTH_8U, 1);
cvResize(imageGray, smallImg, CV_INTER_LINEAR);
cvEqualizeHist(smallImg, smallImg);
CvMemStorage storage = CvMemStorage.create();
if(faceDetector.isNull())
faceDetector = new CvHaarClassifierCascade(cvLoad(dataBase+"\\haarcascade_frontalface_alt.xml"));
CvSeq faces = cvHaarDetectObjects(smallImg, faceDetector, storage, 1.3, number, CV_HAAR_DO_CANNY_PRUNING);
cvClearMemStorage(storage);
int total = faces.total();
for (int i = 0; i < total; i++) {
CvRect r = new CvRect(cvGetSeqElem(faces, i));
cvRectangle(image, cvPoint( r.x()*2, r.y()*2 ),cvPoint( (r.x() + r.width())*2,(r.y() + r.height())*2 ), color, 2, CV_AA, 0);
}
return image;
}//end of face detection
The above method is where the memory leak is found.
Well, the leak has been reduced considerably but there is still a leak that starts small and over time increases the amount of memory that increases per second, The method of capturing video by camera is as follows:
In the detectFace method, free the memory of the IplImage: imageGray and smallImg , I don't know if the increase is due to the IplImage variable of its argument which it returns. But when I remove the detectFace method from the loop the memory usage stays stable. So there is still a leak
In addition to the fact that the detection consumes approximately 30% of the cpu, the video capture also increases the memory very little by little in lapses of time.
For now, what I guess (I did not use OPenCV) is that it is missing to free the memory of the
IplImage
:Missing one:
Also look at the code that calls this method, the one that creates the image passed to it as an argument, should also do the release when it stops using the image.
To detect memory leaks you have many tools at your fingertips but it requires a slightly more methodical process. For example take a look at this article:
https://www.toptal.com/java/hunting-memory-leaks-in-java
It mentions several tips, including:
-verbosegc
.With these tips you will be able to detect memory leaks in your Java application , they will be useful to you in a generic way whether you use OpenCV or not and you will not be blind trying to see where the error is.