自学内容网 自学内容网

QT6.6+Opencv 4.6.0完成摄像头显示以及捕获照片的功能

效果图提前展示,想试试再往下看:
在这里插入图片描述

在网上找了很久QT的摄像头打开方式,成功了,但是捕获照片一直不成功,我不知道是不是qt6版本的原因:这个多媒体窗口我安装没有效果

 QT += multimediawidgets

之前使用过python的opencv,于是想到可以使用opencv来显示摄像头以及捕获照片。环境配置以及安装参考底下这个老哥的,这老哥真的帅,太强了:
安装连接:https://www.cnblogs.com/ybqjymy/p/18070391
完成之后,在打开qt create6,我是6.6版本,其他版本不知道可不可以。
设置ui界面,如图所示:
ui界面效果图
这个是pro文件

//opencv_test.pro
 QT       += core gui multimedia

 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

 CONFIG += c++11

 # The following define makes your compiler emit warnings if you use
 # any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    mainwindow.h

FORMS += \
    mainwindow.ui

//很重要:主要添加这两行,指定头文件路径和库路径
INCLUDEPATH += D:\opencv\opencv\opencv-build\install\include
LIBS += D:\opencv\opencv\opencv-build\install\x64\mingw\lib\libopencv_*.a

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

这个是mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QLabel>
#include <QTimer>
#include <opencv2/opencv.hpp>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void updateCameraFrame();
    void on_pushButton_clicked();


private:
    Ui::MainWindow *ui;
    QLabel *cameraLabel;
    QLabel *cameraLabel2;
    QTimer *timer;
    cv::VideoCapture cap;

    QImage MatToQImage(const cv::Mat &mat);
};

#endif // MAINWINDOW_H

这个是main.cpp

#include "mainwindow.h"

#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

这个是mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <opencv2/opencv.hpp>
#include <QDebug>
#include <QMessageBox>
#include <QDateTime>
#include <QDir>

using namespace cv;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , cap(0) // 打开默认摄像头
{
    ui->setupUi(this);
    cameraLabel = ui->label;
    cameraLabel2 = ui->label_2;


    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &MainWindow::updateCameraFrame);
    timer->start(30); // 更新间隔30ms

    if (!cap.isOpened()) {
        qDebug() << "无法打开摄像头";
        QMessageBox::critical(this, "错误", "无法打开摄像头");
    }

}

MainWindow::~MainWindow()
{
    delete ui;
    cap.release();
    delete timer;
}

void MainWindow::updateCameraFrame()
{
    Mat frame;
    cap >> frame;
    if (frame.empty()) {
        qDebug() << "无法读取数据";
        QMessageBox::critical(this, "错误", "无法从摄像头读取数据");
        return;
    }
    QImage img = MatToQImage(frame);
    cameraLabel->setPixmap(QPixmap::fromImage(img));
}

QImage MainWindow::MatToQImage(const cv::Mat &mat)
{
    if (mat.type() == CV_8UC1) {
        QImage image(mat.cols, mat.rows, QImage::Format_Grayscale8);
        uchar *ptr = image.bits();
        for (int i = 0; i < mat.rows; ++i) {
            memcpy(ptr, mat.ptr(i), mat.cols);
            ptr += image.bytesPerLine();
        }
        return image;
    } else if (mat.type() == CV_8UC3) {
        const uchar *qImgBuf = (const uchar*)mat.data;
        QImage img(qImgBuf, mat.cols, mat.rows, mat.step, QImage::Format_RGB888);
        return img.rgbSwapped();
    } else {
        qDebug() << "cv::Mat image type not handled in switch:" << mat.type();
        return QImage();
    }
}



void MainWindow::on_pushButton_clicked()
{
    Mat frame;
    cap >> frame;
    if (frame.empty()) {
        qDebug() << "无法读取数据";
        QMessageBox::critical(this, "错误", "无法从摄像头读取数据");
        return;
    }
    QImage img = MatToQImage(frame);
    cameraLabel2->setPixmap(QPixmap::fromImage(img));
    QString savePath = "D:/image/";
    QDir dir(savePath);
    if (!dir.exists()) {
        dir.mkpath(savePath);
    }
    QString fileName = QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss") + ".jpg";
    QString filePath = savePath + fileName;

    bool isSaved = cv::imwrite(filePath.toStdString(), frame);

    if (isSaved) {
        QMessageBox::information(this, "图片保存", "图片已成功保存到:" + filePath);
    } else {
        QMessageBox::critical(this, "错误", "保存图片失败");
    }
}

效果图展示:
在这里插入图片描述


原文地址:https://blog.csdn.net/qq_54122113/article/details/140640075

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!