[Qt]使用opencv读取摄像头并显示

—————————-.pro—————————-
QT += core gui
QT += core gui widgets # 确保 widgets 模块被包含

CONFIG += link_pkgconfig
PKGCONFIG += opencv4

QT += multimedia multimediawidgets
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++17

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
CameraWidget.cpp \
main.cpp \
mainwindow.cpp

HEADERS += \
CameraWidget.h \
mainwindow.h

FORMS += \
mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

——————-CameraWidget.h————————
#ifndef CAMERAWIDGET_H
#define CAMERAWIDGET_H

#include
#include
#include
#include
#include

class CameraWidget : public QWidget {
Q_OBJECT

public:
explicit CameraWidget(QWidget *parent = nullptr);

private slots:
void updateFrame();

private:
QLabel *label;
cv::VideoCapture capture;
};

#endif // CAMERAWIDGET_H
————————————CameraWidget.cpp————————
#include “CameraWidget.h”

CameraWidget::CameraWidget(QWidget *parent) : QWidget(parent) {
// 创建布局和标签
QVBoxLayout *layout = new QVBoxLayout(this);
label = new QLabel(this);
layout->addWidget(label);
setLayout(layout);

// 打开摄像头
capture.open(0); // 0 表示默认摄像头
if (!capture.isOpened()) {
label->setText(“无法打开摄像头”);
return;
}

// 设置定时器定时更新摄像头画面
QTimer *timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &CameraWidget::updateFrame);
timer->start(10); // 每 30 毫秒更新一次
}

void CameraWidget::updateFrame() {
cv::Mat frame;
capture >> frame; // 从摄像头获取一帧图像
if (frame.empty()) return;

// 转换为 RGB 格式并显示
cv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);
QImage image(frame.data, frame.cols, frame.rows, frame.step[0], QImage::Format_RGB888);
label->setPixmap(QPixmap::fromImage(image));
}
———————-mainwindow.h——————————
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include

QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
Q_OBJECT

public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();

private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
—————————-mainwindow.cpp————————-
#include “mainwindow.h”
#include “ui_mainwindow.h”

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);

}

MainWindow::~MainWindow()
{
delete ui;
}

————————–main.cpp—————————————
#include
#include “CameraWidget.h”

int main(int argc, char *argv[]) {
QApplication app(argc, argv);
CameraWidget cameraWidget;
cameraWidget.setWindowTitle(“USB 摄像头画面”);
cameraWidget.resize(640, 480);
cameraWidget.show();
return app.exec();
}

发表评论

邮箱地址不会被公开。 必填项已用*标注