【问题标题】:openCV. copy or crop an image from real time feed from web cam, with out memory leak开放式简历。从网络摄像头实时复制或裁剪图像,没有内存泄漏
【发布时间】:2015-01-12 01:09:12
【问题描述】:

我正在尝试寻找一种方法来避免在 while 循环内使用 cvCreateImage,因为我已经意识到这会导致 内存泄漏

我想要this 之类的东西 - 尽管没有内存泄漏。


我不知道为什么这段代码不起作用。

下面的代码是我认为可以工作的,但是运行时会中断。

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((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 ...
}

任何见解都将不胜感激。

【问题讨论】:

    标签: c++ opencv memory-leaks copy


    【解决方案1】:

    任何用 cvCreateImage 分配的图像都需要用 cvReleaseImage 释放。你要发布所有图片吗?

    或者,您可以使用现代 C++ OpenCV api 为您处理所有内存分配和释放。

    【讨论】:

    • 感谢您的回答。我在主要的末尾发布图像。但是,问题是当我尝试在 while 循环下释放 Image 时,它​​会中断。
    【解决方案2】:

    在您的第一段代码中,您尝试将图像复制到空图像。必须为图像分配足够的内存资源。即

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

    这里 notImage 是空的。它没有分配内存。因此您的代码中断。 而在第二种情况下,内存在复制之前分配给 notImage。

    为了避免内存泄漏,试试这个

    IplImage* notImage=cvCloneImage(detectImg);
    

    但记得最后释放图片。

    而不是cvCloneImage,首先创建图像然后使用cvCopyImage复制图像.. 并且新版本的 opencv 提供了更好、更容易的实现..

    http://www.cprogramdevelop.com/4885055/ 上面的链接包含一些有关内存泄漏的信息 希望这会有所帮助

    【讨论】:

    • 非常感谢!似乎解决了。你给我的链接完美地解释了我面临的问题。看起来 cvCloneImage 是泄漏的原因。再次感谢您
    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    相关资源
    最近更新 更多