Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching from OpenCV 3 to OpenCV 4 causes webcam to record at a max of 5 fps instead the usual 30 fps

I'm having some trouble since I changed from OpenCV 3.x to 4.x (compiled from source) in my C++ project. I've replicated this behaviour in a small example that just opens a webcam and records for 5 seconds.

With 3.x I am able to set the webcam framerate to 30 at full hd, but the same code with 4.x just ignores the camera.set(cv::CAP_PROP_FPS,30) and sets it to 5 instead. If I use 720p, the fps is set to 10.

Maybe the code is not relevant here, as it's a classical example, but just in case I'll leave it here.

#include "opencv2/opencv.hpp"
#include "iostream"
#include "thread"
#include <unistd.h>

using namespace cv;

VideoCapture camera(0);
bool stop = false;
int fc = 0;

void saveFrames()
{
    while(!stop)
    {
        Mat frame;
        camera >> frame;
        cv::imwrite("/tmp/frames/frame" + std::to_string(fc) + ".jpg", frame);
        fc++;
    }
}

int main()
{
    if(!camera.isOpened())
        return -1;

    camera.set(cv::CAP_PROP_FRAME_WIDTH,1920);
    camera.set(cv::CAP_PROP_FRAME_HEIGHT,1080);
    camera.set(cv::CAP_PROP_FPS,30);

    double fps = camera.get(cv::CAP_PROP_FPS);
    std::cout << "FPS setting: " << fps << std::endl; // 5 with OCV4, 30 with OCV3

    std::thread tr(saveFrames);
    int waitSeconds = 5;
    usleep(waitSeconds * 1e6);
    stop = true;
    tr.join();

    std::cout << "Written " << fc << " frames of " << fps * waitSeconds << std::endl;
    return 0;
}

Edit: more tests with other computers yield the same result except in a Macbook Pro (but running the same distribution) where OpenCV 4.3 seems to work. The other 2 computers are desktops with usb webcams.

Edit 2: same problem with version 3.4 building from source code. For now, only 3.2 from the repo works ok in the two computers with usbcams.

like image 811
dvilela Avatar asked Jun 01 '20 11:06

dvilela


People also ask

How to increase fps in cv2?

Use threading to obtain higher FPS The “secret” to obtaining higher FPS when processing video streams with OpenCV is to move the I/O (i.e., the reading of frames from the camera sensor) to a separate thread. You see, accessing your webcam/USB camera using the cv2.

Is OpenCV fast?

The OpenCV version ran at an impressive 50 ms per frame and was 6x faster than the reference implementation. Remember, these are both CPU implementations.


1 Answers

This is a known bug that affects OpenCV > 3.3

like image 121
dvilela Avatar answered Sep 22 '22 05:09

dvilela