mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QLabel>
#include <QImage>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
// 用于设置当前帧的函数
void setFrame(const QImage &frame);
private:
// 显示图像的控件
QLabel *imageLabel;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// 创建 QLabel 控件并添加到窗口中
imageLabel = new QLabel(this);
imageLabel->setAlignment(Qt::AlignCenter);
setCentralWidget(imageLabel);
}
void MainWindow::setFrame(const QImage &frame)
{
// 将图像居中显示在我们的 QLabel 控件中
imageLabel->setPixmap(QPixmap::fromImage(frame).scaled(imageLabel->size(),
Qt::KeepAspectRatio,
Qt::FastTransformation));
}
main.cpp
#include <QApplication>
#include <QTimer>
#include "opencv2/opencv.hpp"
#include "mainwindow.h"
using namespace cv;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
// 将 OpenCV 的视频捕获对象初始化为默认的 WebCam
VideoCapture cap(0);
// 如果无法打开摄像头,则输出错误信息
if (!cap.isOpened()) {
qDebug() << "无法打开摄像头!";
return -1;
}
// 创建一个计时器,每隔 10 毫秒更新一次图像
QTimer timer;
timer.start(10);
QObject::connect(&timer, &QTimer::timeout, [&]() {
// 读取当前的帧
Mat frame;
cap.read(frame);
// 如果帧为空,则停止计时器
if (frame.empty()) {
timer.stop();
return;
}
// 将 OpenCV 的 Mat 数据转换为 QImage 图像格式
cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
QImage img((uchar*)frame.data, frame.cols, frame.rows, QImage::Format_RGB888);
// 将图像显示到我们的主窗口
w.setFrame(img);
});
return a.exec();
}