Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

better ways to re-initialize webcam via VideoCapture?

I'm considering a condition: if my computer is running but the USB of a webcam is accidentally unplugged. I want to write something to make the webcam can re-initialize.

int main()
{
   VideoCapture video(0);
    Mat frame;
   while (true) {
       if(video.isOpened()&&video.grab())
       {
           video>>frame;
           if(frame.cols>0)
           imshow("show video",frame);
           waitKey(2);
       }
       else {
               video.release();
               cout<<"wait key input"<<endl;
               char temp[1]; //get a key input
               cin>>temp;
               if(temp[0]!=NULL)
               {
                  VideoCapture video_temp(0);
                  video=video_temp;
               }
       }
   }
}
  1. not sure but it seems video.isOpened() is not always return false even if the USB webcam is not available any more after the webcam first be launched so I may need a video.grab() to do some double check.

  2. in Linux the system can immediately detect the disconnect of webcam. However, in windows system, it takes a while ( about 30 seconds ) to find out that the webcam is disconnected.

is there any better way to make the webcam re-initialize in the program?