In OpenCV—when initializing a VideoCapture object with a USB webcam—once every 2 or 3 runs the camera will fail to initialize. I have this incredibly ugly piece of code to fix that, but maybe somebody knows what can cause the camera init failure and how I can prevent it?
// Initialize video capture
camera_ = cv::VideoCapture(1);
camera_.set(CV_CAP_PROP_CONVERT_RGB , false);
camera_ >> frame_full_;
while (frame_full_.empty()){ // Could be !cap.isOpened
cerr << "Camera failure." << endl;
camera_.release();
camera_ = cv::VideoCapture(1);
camera_.set(CV_CAP_PROP_CONVERT_RGB , false);
camera_ >> frame_full_;
}
/// Do something with the camera feed.
When I close my program, I do get Cleaned up camera. in the console, so I'm thinking it's being released properly.
Added information: On the runs in which the camera fails to init, the call to >>/.read() takes really long to return.
Edit: There is no difference between using the >> operator and .read(), as suggested by @4nonymou5.