开发者

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. I have method1 (see below) that is called from the main program several times. It returns an IplImage that was created inside the method. 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? 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???

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), 开发者_JS百科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.
  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.


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.

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


Memory leaks are removed by creating the dst image outside of the function like this:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜