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();
}
相关推荐
无敌最俊朗@28 分钟前
C++ 序列容器深度解析:vector、deque 与 list
开发语言·数据结构·数据库·c++·qt·list
Da Da 泓29 分钟前
LinkedList模拟实现
java·开发语言·数据结构·学习·算法
Humbunklung1 小时前
VC++ 使用OpenSSL创建RSA密钥PEM文件
开发语言·c++·openssl
Humbunklung1 小时前
填坑:VC++ 采用OpenSSL 3.0接口方式生成RSA密钥
开发语言·c++·rsa·openssl 3.0
Larry_Yanan1 小时前
QML学习笔记(十五)QML的信号处理器(MouseArea)
c++·笔记·qt·学习·ui
zl21878654483 小时前
Playwright同步、异步、并行、串行执行效率比较
开发语言·python·测试工具
Larry_Yanan3 小时前
QML学习笔记(十七)QML的属性变更信号
javascript·c++·笔记·qt·学习·ui
Tony Bai3 小时前
【Go开发者的数据库设计之道】05 落地篇:Go 语言四种数据访问方案深度对比
开发语言·数据库·后端·golang
gopyer3 小时前
180课时吃透Go语言游戏后端开发3:Go语言中其他常用的数据类型
开发语言·游戏·golang·游戏后端开发
come112343 小时前
Go vs. PHP:核心优势劣势对比
开发语言·golang·php