opencv中圖像連續顯示的內存泄露問題的解決辦法

最近在利用opencv做一個視頻檢測模塊,其中涉及到要把檢測後的圖像一幀幀的顯示出來,形成視頻流的感覺。

問題在於如果利用如下的代碼進行連續的圖像顯示,內存泄露非常嚴重,不出幾分鐘,我的4G內存的本本就喫不消了。

原用於連續顯示的代碼:

int i = 0;
IplImage* img = 0;
char *image_name = "D:/project_java/VideoServer/img/1.jpg";
printf("------------- image to video ... ----------------\n");
int isColor = 1;
//創建窗口
cvNamedWindow( "Image", CV_WINDOW_AUTOSIZE );
while(1)
{
   printf("%s%d%s", "image", ++i, ".jpg\n");
   img = cvLoadImage(image_name);
   if((img)
   {
      cvShowImage("Image", img.data);
      char key = cvWaitKey(30);
   }
   else
   {
      printf("Could not load image file...\n");
      cvWaitKey(30);
      //exit(0);
   }
}
cvDestroyWindow("Image");

上面代碼的頭文件是:

#include <cv.h>

#include <highgui.h>

#include <stdio.h>

#include <stdlib.h>

考慮到我用的是最新的opencv2.4.9,裏面有新的圖像讀取和顯示函數,於是我針對上述代碼做了改動:

int i = 0;
//IplImage* img = 0;
Mat img;
char *image_name = "D:/project_java/VideoServer/img/1.jpg";
printf("------------- image to video ... ----------------\n");
//創建窗口
cvNamedWindow( "Image", CV_WINDOW_AUTOSIZE );
while(1)
{
   printf("%s%d%s", "image", ++i, ".jpg\n");
   //img = cvLoadImage(image_name);
   img = imread(image_name);
   //cvShowImage("Image", img.data);
   if((img.data)
   {
       imshow("Image",img);
       char key = cvWaitKey(30);
   }
   else
   {
      printf("Could not load image file...\n");
      cvWaitKey(30);
      //exit(0);
   }
}
cvDestroyWindow("Image");

此時頭文件爲:

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdio.h>
#include <stdlib.h>

using namespace cv;

現在發現內存泄露的問題迎刃而解了。看來學會使用最新的版本還是很重要的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章