c++opencvwebcam-capture

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.


Solution

  • This is a known bug that affects OpenCV > 3.3