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();
}
相关推荐
wjs20242 小时前
状态模式(State Pattern)
开发语言
我命由我123452 小时前
Kotlin 数据容器 - List(List 概述、创建 List、List 核心特性、List 元素访问、List 遍历)
java·开发语言·jvm·windows·java-ee·kotlin·list
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
励志要当大牛的小白菜4 小时前
ART配对软件使用
开发语言·c++·qt·算法
爱装代码的小瓶子6 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
Maybe_ch7 小时前
.NET-键控服务依赖注入
开发语言·c#·.net
超浪的晨7 小时前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
终焉暴龙王7 小时前
CTFHub web进阶 php Bypass disable_function通关攻略
开发语言·安全·web安全·php
Edingbrugh.南空8 小时前
Aerospike与Redis深度对比:从架构到性能的全方位解析
java·开发语言·spring
CodeCraft Studio9 小时前
借助Aspose.HTML控件,在 Python 中将 HTML 转换为 Markdown
开发语言·python·html·markdown·aspose·html转markdown·asposel.html