1 OpenCV打开摄像头显示摄像头帧率

通过OpenCV打开摄像头,并获取摄像头的视频帧进行显示或者继续进一步后处理,我们都希望显示当前的帧率,特别是对于实时性要求较高的应用,比如说实时目标检测,下面给出了一段显示OpenCV摄像头帧率的示例代码,可供参考。

#include <iostream>
#include <chrono>

#include <opencv2/opencv.hpp>


int main()
{
    cv::VideoCapture camera_reader;
    camera_reader.set(cv::CAP_PROP_FRAME_WIDTH, 640); //设置宽度
    camera_reader.set(cv::CAP_PROP_FRAME_HEIGHT, 480); //设置长度
    camera_reader.set(cv::CAP_PROP_FOURCC, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'));
    camera_reader.set(cv::CAP_PROP_FPS, 30); // 帧率

    camera_reader.open(0);

    int camera_fps = 0;
    while (camera_reader.isOpened())
    {
        auto beforeTime = std::chrono::steady_clock::now();

        cv::Mat input_frame;
        camera_reader.read(input_frame);

        if (input_frame.empty())
            break;

        // 视频帧上增加FPS
        std::string str = "FPS:" + std::to_string(camera_fps);
        cv::putText(input_frame, str.c_str(), cv::Point(10, 30), cv::FONT_HERSHEY_COMPLEX, 1, cv::Scalar(0, 255, 255), 2, 8, 0);


        cv::imshow("camera", input_frame);
        if (27 == cv::waitKey(33))
            break;

        auto afterTime = std::chrono::steady_clock::now();

        double duration_millsecond = std::chrono::duration<double>(afterTime - beforeTime).count();

        camera_fps = int(1 / duration_millsecond);
    }

    cv::destroyWindow("camera");
    camera_reader.release();

    return 0;
}

在上述代码中,我们使用std::chrono计算每一帧的耗时,然后计算每一次的帧率,帧率显示的示例图片如下:

OpenCV – OpenCV打开摄像头显示摄像头帧率-StubbornHuang Blog