Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

videocapture.read() returning black frame if camera did not have time to initialize

Hi, I am currently working on a camera capture project. The problem is, even though camera gets opened correctly, sometimes the cap.read(frame) returns a black frame. After some tests, I noticed that putting a Sleep of 1-2 seconds after cap.open() solves the problem. Without sleep, seems like that cap.read() is performed before that the camera is actually ready for capture. But instead of failing and returning false, it just grabs a black frame. Also, checking for frame.empty() does not work, since frame is not empty, it is just all black.

Any idea on how to solve this, of course without having to sleep for a while after camera open?

#include <opencv2/objdetect/objdetect.hpp>
  #include <opencv2/highgui/highgui.hpp>
  #include <opencv2/imgproc/imgproc.hpp>
  #include <Windows.h>

  // .......... previous not relevant code

    VideoCapture cap;
    cap.open(0); // open the default camera
    if (cap.isOpened()) // check if we succeeded
    {
      // Sleep(2000);
      Mat frame;
      while (!cap.read(frame))
      {
        MessageBoxA(0, "unable to read frame", "CamDll", 0);
      }
      // Process frame data...
    }