我使用它创建了一个非常简单的 UI,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;
}
捕获帧后,必须将其转换为 aQImage
才能显示在标签中。为了实现这一点,我使用以下方法:
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)的视频捕获流反复打开和关闭。表明网络摄像头已打开的蓝色环反复闪烁,这一事实证明了这一点。这导致网络摄像头视频流标签的刷新率非常低,这是不可取的。是否有某种方法可以使网络摄像头流保持打开状态以防止这种“闪烁”发生?