opencv: VideoCapture has Memory leak in opencv4.0.0

  • OpenCV => 4.0.0
  • Operating System / Platform => Windows 64 Bit
  • Compiler => Visual Studio 2015

In the following code, the memory will increase slowly along with the time elapsed.

int main()
{
	cv::VideoCapture cap;
	cv::Mat frame;
	while (true) {
		cap.open(0);
		cap >> frame;
		cv::imshow("vidoe", frame);
		cv::waitKey(10);
		cap.release();
	}
	return 0;
}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 18 (8 by maintainers)

Most upvoted comments

I confirm memory leak. Not sure about DSHOW, but MSMF backend consume a lot of memory. If DSHOW used mem leak is (or is it not leak) 5 Kb per 1000 iteration. 1 time (from 3) app was terminated, unfortunately I dont remember error code. And if MSMF used - 550 Mb(1) memory leak for 1000 iteration. Also if used MSMF cap.release(); produce to std output warning [ WARN:0] terminating async callback, sometime [ WARN:x], x=1…5

OpenCV 3.4 build ccf96b9e050a1d99cf5f053d13958dc39d4b5609 Win 10 x64, VS 15.9.2

Code used for test:

cv::VideoCapture cap;
cv::Mat frame;
int iBackend = cv::CAP_MSMF;//or CAP_MSMF
cap.open(0, iBackend);
cap >> frame;
cap.release();
std::cout << "wait Enter";
getchar(); //check mem size here
std::cout << "start";
for (int i = 0; i < 1000;++i) {
	cap.open(0, iBackend);
	cap >> frame;
	cap.release();
}
std::cout << "end"; //end here
getchar();

Good to know the leak is confirmed. We had switch to thread pool to avoiding frequently creating/destroying thread with VideoCapture. This could be a temporary option.

Exactly same problem than @Bleach665 using 4.0.0 Windows 10 x64

@yanchao12122 Could you please verify the following

  1. If you remove cv::imshow("vidoe", frame); is the memory leak still present?
int main()
{
	cv::VideoCapture cap;
	cv::Mat frame;
	while (true) {
		cap.open(0);
		cap >> frame;
		cap.release();
	}
	return 0;
}
  1. If you only open capture once, is the memory leak still present?
int main()
{
	cv::VideoCapture cap;
	cv::Mat frame;
	cap.open(0);
	while (true) 
        {
	      if(!cap.read(frame))
              {
                  break;
              }
	}
	return 0;
}