释放返回值/指向CvMat的指针的内存

时间:2012-07-18 14:46:30

标签: c++ opencv

我遇到了使用OpenCV释放内存的问题。 如何释放返回指针的内存?

这是我的代码:

这是我调用函数细化的函数:

int preprocessing_and_classification() { 

/// Section 2D - Perform morphological processing 

            CvMat* image1_edge_morpho = thinning(image1_edge); 
                        ....... 
                        ....... 
                        ........... 

                        //////////////// release the memory /////////////// 
            cvReleaseImage(&img); 
            cvReleaseMat(&image1); 
            cvReleaseMat(&image1_edge); 
            cvReleaseMat(&image1_edge_morpho); 
            cvReleaseImage(&imgg); 
            cvReleaseImage(&imggT); 
            cvReleaseMemStorage(&g_storage); 
            cvReleaseMat(&features); 
            cvReleaseMat(&labels_obtained); 
            ///////////////////////////////////////////////////// 
return num_bacilli; 

} 

您可以在下面看到的函数细化返回Pointer Merode:

CvMat* thinning(CvMat* M){ 

/* 
Input parameters 
CvMat* M = Pointer to the matrix on which morphological processing needs to be done. 

Output parameters 
CvMat* Merode = Pointer to morphological processed matrix. 
*/ 



    CvMat* Merode = cvCreateMat(h,w,CV_8UC1); 
    . 
    . 
    . 
    . 
    . 
    . 



    ///// Releasing the images, matrices and structuring elements to free memroy. 
   // Matrix Merode is not released as it is the output of this function file 
    cvReleaseStructuringElement(&B); 
    cvReleaseMat( &Mopen ); 
    cvReleaseMat( &temp ); 
    cvReleaseMat( &Mclose ); 
    cvReleaseMat( &temp1 ); 
    cvReleaseMat( &MM ); 
    cvReleaseImage( &img1 ); 
    cvReleaseMemStorage(&g_storage); 
    cvReleaseMat( &Mimg1 ); 
    cvReleaseMat( &Mimg2 ); 


    return Merode; 
} 

如何删除Merode?

1 个答案:

答案 0 :(得分:0)

如果您允许更改thinning功能,则可以使用cv::Matcv::Ptr<cvMat>(甚至std::unieue_ptrstd::shared_ptr使用自定义删除功能c ++ 11兼容编译器的情况)

如果您不允许更改代码,则应在任何使用该方法的地方删除返回的指针。最简单的方法是用cv::Ptr<>包装指针。