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

asked 2016-01-14 10:43:51 -0600

Viotto gravatar image

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...
    }
edit retag flag offensive close merge delete

Comments

It's often like this with usb Cam; with my camera I discard some frames (less than 10). you should try a loop like this

int n=10;
for (int i=0;<n;i++)
{
cap.read(frame);
cout<< mean(frame)<<endl;
}

try to adjust n

LBerger gravatar imageLBerger ( 2016-01-14 13:34:25 -0600 )edit

Thanks for comment, but this is more a workaround than a solution. Same thing as I did, by sleeping for a few until successful capture.

Viotto gravatar imageViotto ( 2016-01-15 07:01:56 -0600 )edit

I don't think there is a software answer to this problem. It's a hardware problem.

LBerger gravatar imageLBerger ( 2016-01-15 10:57:26 -0600 )edit