Search code examples
c++opencvframe-rateopencv3.1

How to calculate the fps of a video (with processing) using opencv


I can't seem to figure out what is wrong with the code fragment I have...it keeps on outputting over 200 fps for some reason. I tested with OpenCV and the unprocessed video is about 30 fps.

int n_frame = 0;
Mat previous;
auto start = chrono::high_resolution_clock::now();
while (m_cap.isOpened()) {
    if (n_frame % 100 == 1) {
        auto end = chrono::high_resolution_clock::now();    
        auto time = chrono::duration_cast<chrono::seconds>(end - start);
        cout << "the fps is: " << 1.0 / (static_cast<double>(time.count()) / n_frame) << endl;
        //cin.ignore(1000, '\n');
    }
    n_frame++;
    cout << "frame number: " << n_frame << endl;
    Mat frame, original;

    m_cap >> frame;
    if (frame.empty())
        break;


//do some video processing down here eg thresholding
}

Solution

  • I think you forgot to re-initialize the start time, here is modified code, this provides consistent fps value, I tested in my laptop and got around 33.2, I just count up to 100 frames and reinitialize everything, this seems to work

    int n_frame = 0;
    Mat previous;
    auto start = std::chrono::high_resolution_clock::now();
    VideoCapture m_cap(0);
    
    while (m_cap.isOpened()) {
        n_frame++;
        if (n_frame == 100) {
            auto end = std::chrono::high_resolution_clock::now();
            auto time = std::chrono::duration_cast<chrono::seconds>(end - start);
            cout << "the fps is: " << (n_frame / static_cast<double>(time.count())) << endl;
            start = end;
            n_frame = 0;
        }
        //cout << "frame number: " << n_frame << endl;
        Mat frame, original;
        m_cap >> frame;
        if (frame.empty())
            break;
    }