简体   繁体   中英

openCV. copy or crop an image from real time feed from web cam, with out memory leak

I am trying to find a way to avoid the use of cvCreateImage inside of a while loop, because I have realized that this will cause a memory leak .

I would like something like this - albeit with out the memory leak.


I don`t know why this code is not working.

The code below is what I thought that would work however it breaks when run.

if((capture = cvCreateCameraCapture(0)) == NULL) {
    printf("connect cam first\n");
    return -1;
}
IplImage *detecImg = cvCreateImage( cvSize(WIDTH, HEIGHT), 8, 1 );  
IplImage *frameImage = NULL;
IplImage *notImage = NULL;  
while(1){
    cvWaitKey(1);   
    cvSplit(frameImage, a, b, c, NULL);
    //detect objec from a,b,c.....output is "detecImg"
    cvSetImageROI(detectImg, Roi);  //Roi is changing depends on detection result
    notImage=cvCloneImage(detectImg);//cvCloneImage,cvCopy not working...
    cvNot(notImage, notImage);
    copyNotImg = cvCloneImage(notImage);

    ... continues ...

}

If I use this code below it works fine but leaks a little memory.

if((capture = cvCreateCameraCapture(0)) == NULL) {
    printf("connect cam first\n");
    return -1;
}
IplImage *detecImg = cvCreateImage(cvSize(WIDTH, HEIGHT), 8, 1);    
IplImage *frameImage = NULL;
IplImage *notImage = NULL;  
while(1){
    cvWaitKey(1);   
    cvSplit(frameImage, a, b, c, NULL);
    //detect objec from a,b,c.....output is "detecImg"
    cvSetImageROI( detectImg, Roi);  //Roi is changing depends on detection result
    notImage=cvCreateImage( cvSize(Roi.width, Roi.height), 8, 1  );
    cvNot(notImage, notImage);
    copyNotImg= cvCloneImage(notImage);

    ... continues ...
}

Any insight would appreciated.

Any images allocated with cvCreateImage need to be released with cvReleaseImage. Are you releasing all images?

Alternatively, you could use the modern C++ OpenCV api which handles all memory allocation and deallocation for you.

In your first piece of code, you are trying to copy image to a null image. Image must be allocated sufficient memory resources. ie

IplImage *notImage = NULL;
notImage=cvCloneImage(detectImg);

Here notImage is empty. It has no memory assigned to. hence your code breaks. whereas in second case memory is assigned to notImage before copying.

to avoid memory leaks try this

IplImage* notImage=cvCloneImage(detectImg);

but remember to release the image in the end.

Instead of cvCloneImage, First create image then use cvCopyImage to copy the image.. And new version of opencv provides better and easier implimentations..

http://www.cprogramdevelop.com/4885055/ the above link contains some info regarding memory leaks Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM