I want to take single frames from a Logitech C300 webcam using openCV. When I use the code below. Images are saved but, in about 50% of the cases they contain errors (see image).
I now have been searching for hours, but as I don't know what is causing it, I'm not sure which keyword may help for searching. For me it looks as if the image from the webcam is read while the camera is still updating the frame (but's just a guess). I tested uvccapture which produces the same problems (but less often) with standard options, but works without problems when using the -m option. According to the man-page it's "Toggles capture mode to YUYV capture".
So my question is, is there a way to use this mode with openCV too? I would like to avoid using v4l2 directly.
VideoCapture cap(0);
if(!cap.isOpened())
cout << "Opening video device failed" << endl;
cap.set(CV_CAP_PROP_FRAME_WIDTH, 1280);
cap.set(CV_CAP_PROP_FRAME_HEIGHT, 1024);
Mat frame;
for(int i = 0; i<50; i++)
{
stringstream str;
str << "/home/ubuntu/image" << i<< ".jpg";
cap >> frame;
imwrite(str.str(), frame);
cout << i << endl;
}
return 0;
I found another thread here which states that the implementation of how the frames are captured by openCV may be the culprit:
OpenCV calls on video-4-linux (v4l2) to request RGB frames from the camera. My camera was delivering JPEG compressed images which v4l2 was decompressing using a very slow software decoder.
I am using a BeagleBoard and when using the (convenient) openCV-functions I had the mentioned problems. I tried the program Martin Fox linked in the thread, which takes YUV-frames from the webcam directly with v4l2. Now it is possible to get pictures up to 1280x1024 pixels without problems what is the resolution of the webcam's sensor.