qt5+opencv4调用摄像头

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();
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值