Qt OpenCV网络摄像头流打开和关闭

Qt OpenCV Webcam Stream Opening and Closing

本文关键字:OpenCV 网络 摄像头 Qt      更新时间:2023-10-16

我使用Qt创建了一个非常简单的UI,它由一个简单的按钮和一个标签组成。当发出按钮的clicked()信号时,将调用使用OpenCV从网络摄像头捕获帧的函数。我目前用于实现此目的的代码是:

cv::Mat MainWindow::captureFrame(int width, int height)
{
    //sets the width and height of the frame to be captured
    webcam.set(CV_CAP_PROP_FRAME_WIDTH, width);
    webcam.set(CV_CAP_PROP_FRAME_HEIGHT, height);
    //determine whether or not the webcam video stream was successfully initialized
    if(!webcam.isOpened())
    {
        qDebug() << "Camera initialization failed.";
    }
    //attempts to grab a frame from the webcam
    if (!webcam.grab()) {
        qDebug() << "Failed to capture frame.";
    }
    //attempts to read the grabbed frame and stores it in frame
    if (!webcam.read(frame)) {
        qDebug() << "Failed to read data from captured frame.";
    }
    return frame;
}

捕获帧后,必须将其转换为QImage才能显示在标签中。为了实现这一点,我使用以下方法:

QImage MainWindow::getQImageFromFrame(cv::Mat frame) {
    //converts the color model of the image from RGB to BGR because OpenCV uses BGR
    cv::cvtColor(frame, frame, CV_RGB2BGR);
    return QImage((uchar*) (frame.data), frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
}

我的 MainWaindow 类的构造函数如下所示:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    resize(1280, 720);
    move(QPoint(200, 200));
    webcam.open(0);
    fps = 1000/25;
    qTimer = new QTimer(this);
    qTimer->setInterval(fps);
    connect(qTimer, SIGNAL(timeout()), this, SLOT(displayFrame()));
}

QTimer应该通过调用dislayFrame()来显示帧

void MainWindow::displayFrame() {
    //capture a frame from the webcam
    frame = captureFrame(640, 360);
    image = getQImageFromFrame(frame);
    //set the image of the label to be the captured frame and resize the label appropriately
    ui->label->setPixmap(QPixmap::fromImage(image));
    ui->label->resize(ui->label->pixmap()->size());
}

每次发出其timeout()信号时。然而,虽然这似乎在一定程度上有效,但实际发生的是来自我的网络摄像头(罗技 Quickcam Pro 9000)的视频捕获流反复打开和关闭。表示网络摄像头已打开的蓝色环反复闪烁的事实证明了这一点。这会导致网络摄像头视频流标签的刷新率非常低,并且是不可取的。有没有办法使网络摄像头流保持打开状态,以防止这种"闪烁"发生?

我似乎通过删除行解决了网络摄像头流打开和关闭的问题:

webcam.set(CV_CAP_PROP_FRAME_WIDTH, width);
webcam.set(CV_CAP_PROP_FRAME_HEIGHT, height);

captureFrame() 函数并设置要在 MainWindow 构造函数中捕获的帧的宽度和高度。