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

时间:2013-10-18 23:05:06

标签: c++ qt opencv video-streaming video-capture

我使用Qt创建了一个非常简单的用户界面,其中包含一个简单的按钮和一个标签。当发出按钮的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()信号。 然而,虽然这似乎在一定程度上起作用,但实际发生的是来自我的网络摄像头的视频捕获流( Logitech Quickcam Pro 9000 )反复打开和关闭。事实证明,指示网络摄像头开启的蓝色环反复闪烁。这导致网络摄像头视频流标签的刷新率非常低,并且是不期望的。是否有某种方法可以使网络摄像头流保持打开状态以防止发生这种“闪烁”?

1 个答案:

答案 0 :(得分:1)

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

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

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