欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > qt5.14.2 opencv调用摄像头显示在label

qt5.14.2 opencv调用摄像头显示在label

2025/7/3 12:59:39 来源:https://blog.csdn.net/ivanwfy/article/details/148013818  浏览:    关键词:qt5.14.2 opencv调用摄像头显示在label

ui界面添加一个Qlabel名字是默认的label

还有一个button名字是pushButton

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
#include <opencv2/opencv.hpp>  // 添加OpenCV头文件
#include <QTimer>              // 添加定时器头文件QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACEclass MainWindow : public QMainWindow
{Q_OBJECTpublic:MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void on_pushButton_clicked();void updateFrame();  // 新增的帧更新槽函数private:Ui::MainWindow *ui;cv::VideoCapture cap;  // OpenCV视频捕获对象QTimer *timer;         // 定时器对象
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <opencv2/opencv.hpp>
#include <QTimer>
#include <QImage>
#include <QPixmap>MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{ui->setupUi(this);// 初始化定时器timer = new QTimer(this);// 连接信号和槽connect(timer, &QTimer::timeout, this, &MainWindow::updateFrame);// 设置Label的缩放策略ui->label->setScaledContents(true);
}MainWindow::~MainWindow()
{// 释放资源if(cap.isOpened()) {cap.release();}if(timer->isActive()) {timer->stop();}delete ui;
}void MainWindow::on_pushButton_clicked()
{if (!timer->isActive()) {// 尝试打开摄像头cap.open(0); // 0表示默认摄像头if (!cap.isOpened()) {ui->label->setText("无法打开摄像头");return;}// 设置摄像头分辨率(可选)cap.set(cv::CAP_PROP_FRAME_WIDTH, 640);cap.set(cv::CAP_PROP_FRAME_HEIGHT, 480);timer->start(30); // 每30毫秒更新一帧ui->pushButton->setText("停止摄像头");} else {// 停止摄像头timer->stop();cap.release();ui->pushButton->setText("启动摄像头");ui->label->clear();}
}void MainWindow::updateFrame()
{cv::Mat frame;cap >> frame; // 从摄像头获取一帧if (!frame.empty()) {// 将OpenCV的BGR格式转换为RGBcv::cvtColor(frame, frame, cv::COLOR_BGR2RGB);// 将cv::Mat转换为QImageQImage img(frame.data,frame.cols,frame.rows,frame.step,QImage::Format_RGB888);// 将QImage转换为QPixmap并显示在Label上ui->label->setPixmap(QPixmap::fromImage(img));}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词