I am trying to write the frames that come in from a stream to an external hard disk conencted via USB in .jpg format. But I observe a memory leak when I run this C++ program. The interesting point is that when I overwrite the same image file(same name and path) I don't see a memory leak, but I write new file(new name and path) for every incoming frame, my computer's RAM gets filled up. I am using a single cv::Mat initialised at the start of the program and storing each incoming frame in that Mat. And then I write this Mat to the disk using cv::imwrite. I don't know why this is happening. Can you guys suggest something?
Here is the code:
#include "opencv2/opencv.hpp"
#include <iostream>
using namespace std;
using namespace cv;
int main(){
VideoCapture cap("testVid.mp4");
if(!cap.isOpened()){
cout << "Error opening video stream or file" << endl;
return -1;
}
Mat *writeMat = new Mat();
int frame_num = 0;
while(1){
cap >> *writeMat;
if (writeMat->empty())
break;
char *imageName = (char*)malloc(64*sizeof(char));
//Storage mounted at /mnt/disk1
sprintf(imageName, "/mnt/disk1/%07d.jpg", frame_num);
imwrite(imageName, *writeMat);
free(imageName);
}
cap.release();
delete writeMat;
writeMat = NULL;
return 0;
}