OpenCV:VideoCapture::get(CV_CAP_PROP_FPS) 返回 0 FPS

2022-01-08 00:00:00 opencv windows camera c++ avi

我正在尝试从我的相机中获取 fps,以便我可以将其传递给 VideoWriter 以输出视频.但是,我通过从我的相机调用 VideoCapture::get(CV_CAP_PROP_FPS) 得到 0 fps.如果我对其进行硬编码,我的视频可能会太慢或太快.

I am trying to get the fps from my camera so that I can pass it to the VideoWriter for outputting the video. However, I am getting 0 fps by calling VideoCapture::get(CV_CAP_PROP_FPS) from my camera. If I hardcode it, my video may be too slow or too fast.

#include "opencv2/opencv.hpp"
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
    cv::VideoCapture cap;
    int key = 0;

    if(argc > 1){
        cap.open(string(argv[1]));
    }
    else
    {
        cap.open(CV_CAP_ANY);
    }
    if(!cap.isOpened())
    {
        printf("Error: could not load a camera or video.
");
    }

    Mat frame;
    cap >> frame;
    waitKey(5);

    namedWindow("video", 1);
    double fps = cap.get(CV_CAP_PROP_FPS);
    CvSize size = cvSize((int)cap.get(CV_CAP_PROP_FRAME_WIDTH),(int)cap.get(CV_CAP_PROP_FRAME_HEIGHT));

    int codec = CV_FOURCC('M', 'J', 'P', 'G');
    if(!codec){ waitKey(0); return 0; }
    std::cout << "CODEC: " << codec << std::endl;
    std::cout << "FPS: " << fps << std::endl;
    VideoWriter v("Hello.avi",-1,fps,size);
    while(key != 'q'){
        cap >> frame;
        if(!frame.data)
        {
            printf("Error: no frame data.
");
            break;
        }
        if(frame.empty()){ break; }
        v << frame;
        imshow("video", frame);
        key = waitKey(5);
    }
    return(0);
}

如何让 VideoCapture::get(CV_CAP_PROP_FPS) 返回正确的 fps 或为 VideoWriter 提供适用于所有网络摄像头的 fps?

How can I get VideoCapture::get(CV_CAP_PROP_FPS) to return the right fps or give a fps to the VideoWriter that works universally for all webcams?

推荐答案

据我所知,CV_CAP_PROP_FPS 仅适用于视频.如果您想从网络摄像头捕获视频数据,您必须自己正确计时.例如,使用计时器每 40 毫秒从网络摄像头捕获一帧,然后保存为 25fps 视频.

CV_CAP_PROP_FPS only works on videos as far as I know. If you want to capture video data from a webcam you have to time it correctly yourself. For example use a timer to capture a frame from the webcam every 40ms and then save as 25fps video.

相关文章