简体   繁体   中英

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; 
    }
}

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

You cannot set frame rate for camera feeds as they are simply piped in when they are requested by your code. You can put a delay into your code to only request them every 1s which I think would be helpful for your use case.

See below code.

VideoCapture cap(0);

while (1) {

 Mat frame; bool bSuccess = cap.read(frame); imshow("MyVideo", frame); //This Sets the Frame Rate to 1000ms (1s) cv::waitKey(1000); 

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM