Qt使用opencv打开摄像头

1.效果图

2.代码

cpp 复制代码
#include "widget.h"

#include <QApplication>


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

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


using namespace cv;
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    // 创建一个 QLabel 用于显示图像
    QLabel label;
    label.resize(640, 480); // 可根据需要进行调整
    label.show();

    // 打开摄像头
    cv::VideoCapture capture(0);
    if (!capture.isOpened()) {
        qDebug("Failed to open camera.");
        return -1;
    }

    // 使用 QTimer 定期更新图像显示
    QTimer timer;
    QObject::connect(&timer, &QTimer::timeout, [&]() {
        cv::Mat frame;
        capture >> frame; // 获取一帧图像

        if (!frame.empty()) {
            // 将 OpenCV 的图像转换为 Qt 的 QImage
            QImage image(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
            image = image.rgbSwapped(); // BGR 转 RGB

            // 将 QImage 设置到 QLabel 上显示
            label.setPixmap(QPixmap::fromImage(image).scaled(label.size(), Qt::KeepAspectRatio));
        }
    });

    // 每秒更新一次图像显示
    timer.start(1000 / 30); // 30 fps
    return a.exec();
}
相关推荐
lkbhua莱克瓦248 分钟前
Java基础——集合进阶3
java·开发语言·笔记
多喝开水少熬夜27 分钟前
Trie树相关算法题java实现
java·开发语言·算法
QT 小鲜肉29 分钟前
【QT/C++】Qt定时器QTimer类的实现方法详解(超详细)
开发语言·数据库·c++·笔记·qt·学习
MeowKnight95831 分钟前
【Qt】Qt实践记录3——UDP通信
笔记·qt
lsx2024061 小时前
MySQL WHERE 子句详解
开发语言
Tony Bai1 小时前
【Go模块构建与依赖管理】09 企业级实践:私有仓库与私有 Proxy
开发语言·后端·golang
Lucky小小吴1 小时前
开源项目5——Go版本快速管理工具
开发语言·golang·开源
Mr.Jessy1 小时前
Web APIs 学习第五天:日期对象与DOM节点
开发语言·前端·javascript·学习·html
杨福瑞2 小时前
数据结构:单链表(2)
c语言·开发语言·数据结构
进化中的码农2 小时前
Go中的泛型编程和reflect(反射)
开发语言·笔记·golang