Search code examples
c++opencvvideo-capture

OpenCV isn't saving 2nd webcam picture after taking 1st webcam picture


I'm trying to take two pictures in quick succession using a webcam. Here's the code I've written to do that:

#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <iostream>
#include <Windows.h>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    Mat frame;
    VideoCapture cap(0);

    if (!cap.isOpened()) cout << "it ain't open.\n";

    cap.set(CV_CAP_PROP_FRAME_WIDTH,  300);
    cap.set(CV_CAP_PROP_FRAME_HEIGHT, 300);
    namedWindow("1", CV_WINDOW_AUTOSIZE);

    printf("before\n");
    cout << "read 1 status: " << cap.read(frame) << endl;
    imshow("1", frame);
    while (1){
        if (waitKey(27) >= 0){
            destroyAllWindows();
            break;
        }
    }

    printf("after 1\n");

    Mat frame2;
    namedWindow("2", CV_WINDOW_AUTOSIZE);
    cout << "read 2 status: " << cap.read(frame2) << endl;
    imshow("2", frame2);
    while (1){
        if (waitKey(27) >= 0){
            destroyAllWindows();
            break;
        }
    }

    printf("after 2\n");

    getchar();

    return 0;
}

This takes the first picture without trouble:

first picture taken

...but the second picture, after moving the camera far to the left, is still the first picture:

what should be the second picture

Here's the printed output after both pictures are taken, which seems to suggest that read() is working properly:

before
read 1 status: 1
after 1
read 2 status: 1
after 2

Any idea what I'm missing?

EDIT: Marol provided the answer to this question. When capturing the second frame, I take two pictures, saving both to the same Mat:

Mat frame2;
namedWindow("2", CV_WINDOW_AUTOSIZE);
cout << "read 2 status: " << cap.read(frame2) << endl;
cout << "read 3 status: " << cap.read(frame2) << endl;
imshow("2", frame2); 

The pictures are clearly different this time.


Solution

  • It does return two different pictures. Try do rapid movement during the moment the first picture is taken. You can see that frame1 is different than frame 2, although in fact frame2 comes from the different time you expect. In case of my simple webcam, it does buffer two frames at one point in time (I mean one frame and immediately second frame after first one).

    Solution will be to discard even number of frames (second, fourth etc.) and consider only odd ones (first, third, etc.).