Search code examples
c++opencvvideoframe-rate

How to capture video with OpenCV in c++ with a desired fps


i need to take one frame for second with OpenCV. The problem is that VideoCapture::get(CV_CAP_PROP_FPS); always returns 0. And if i try to set the desired fps with VideoCapture::set nothing change.

This is my code:

VideoCapture cap(0); 

if (!cap.isOpened()) {
    cout << "Cannot open the video cam" << endl;
    return -1;
}

double dWidth = cap.get(CV_CAP_PROP_FRAME_WIDTH);
double dHeight = cap.get(CV_CAP_PROP_FRAME_HEIGHT);
double fps = 1;
cap.set(CV_CAP_PROP_FPS, fps);
cout << "FPS : " << fps << endl;

cout << "Frame size : " << dWidth << " x " << dHeight << endl;


namedWindow("CAPTURE EXPRESSION",CV_WINDOW_AUTOSIZE);     
while (1) {
    Mat frame;

    bool bSuccess = cap.read(frame);

    if (!bSuccess) {
        cout << "Cannot read a frame from video stream" << endl;
        break;
    }
    fps = cap.get(CV_CAP_PROP_FPS);
    imshow("MyVideo", frame); 
    cout << "FPS : " << fps << endl;

    if (waitKey(30) == 27) {
        cout << "esc key is pressed by user" << endl;
        break; 
    }
}

P.S. i'm using OpenCV 2.4.9 with a Mac OS, and with the integrated camera of the MacBook


Solution

  • This set and get of fps always mess up, even when I used to trail, they are kind of random, a proper explanation from someone would be an interesting thing to read at. It might have some dependencies on the video container.

    But, I don't think the set parameters of fps is applicable for live cam, its like asking the world in front of webcam to run slowly, which won't happen. The other way around is storing the live frames in a buffer and displaying as per your required speed. I don't think opencv would do that. So, if you want a slower rate, record the video and then, set fps and check on the recorded video.

    And waitKey, with a higher number, in case of live stream, skips the frames in-between interval, so use it only, if you think, it helps you.