简体   繁体   English

如果返回了图像,我是否需要cvReleaseImage?

[英]Do I need a cvReleaseImage if image is returned?

I'm working with OpenCV 2.2 and I'm wondering if I have to release the memory I allocated for an image if the image is returned. 我正在使用OpenCV 2.2,我想知道如果返回图像,是否必须释放分配给图像的内存。 I have method1 (see below) that is called from the main program several times. 我有多次从主程序调用的method1(请参见下文)。 It returns an IplImage that was created inside the method. 它返回在方法内部创建的IplImage。 Where do I have to release the image created in the method? 我必须在哪里释放在方法中创建的图像? If I release it before the return command nothing will be returned I guess? 如果我在return命令之前释放它,我猜不会返回任何内容吗? After the return command, it will not be processed. 返回命令后,将不对其进行处理。 So how do I get rid of all the dst Images created during runtime of my program??? 那么如何摆脱程序运行时创建的所有dst图像?

IplImage* Method1(IplImage* src) {
 IplImage *dst = cvCreateImage(cvSize(src->width, src->height), IPL_DEPTH_8U, 1);
 [...]
 return dst;
}

Thx! 谢谢!

EDIT: So should I call this method like this: 编辑:所以我应该这样调用此方法:

IplImage* tmp;
tmp = cvCreateImage(cvSize(dst->width, dst->height), IPL_DEPTH_8U, 1);
tmp = Method1(src);

or 要么

IplImage* tmp;
tmp = Method1(src);

to release the memory correctly in the main program afterwards? 之后在主程序中正确释放内存?

  1. If you're using C++, don't use IplImage* , use cv::Mat , which does memory management automatically for you. 如果您使用的是C ++,请不要使用IplImage* ,而应使用cv::Mat ,它会自动为您进行内存管理。
  2. Your first method creates a memory leak (this is not opencv-specific - you allocate the memory for something, then overwrite the pointer so it's now inaccessible (this means you have an allocation that does nothing, and you will never be able to free that. 您的第一种方法会产生内存泄漏(这不是opencv特有的-您为某事分配内存,然后覆盖指针,使其现在不可访问(这意味着您有什么都不做的分配,并且您将永远无法释放该内存) 。

No, otherwise you'd return a pointer to some freed memory. 不,否则您将返回一个指向一些已释放内存的指针。 Just make sure the name Method1 indicates that you're returning a new image that should be released later on. 只需确保名称Method1指示您正在返回一个新图像,该图像稍后应发布。

You'll have to release it somewhere outside (once you're done with it). 您必须将其释放到外面的某个地方(一旦完成)。

You can allocate memory within the function. 您可以在函数内分配内存。 Once you returned the image in the calling function after using dst you can call cvReleaseImage( &dst ) to clear the memory 使用dst后在调用函数中返回图像后,可以调用cvReleaseImage(&dst)清除内存

Memory leaks are removed by creating the dst image outside of the function like this: 通过在函数外部创建dst映像,可以消除内存泄漏,如下所示:

void Method1(IplImage* src, IplImage* &dst) {
 [...]
}

IplImage* image0 = ...;
IplImage* image1 = cvCreateImage(cvSize(image0->width, image0->height), IPL_DEPTH_8U, 1);
Method1(image0, image1);   

And don't forget to use cvReleaseImage(&...) on both of the images afterwards. 并且不要忘了之后在两个图像上都使用cvReleaseImage(&...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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