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();
}
相关推荐
我能坚持多久3 分钟前
D20—C语言文件操作详解:从基础到高级应用
c语言·开发语言
橘子师兄19 分钟前
C++AI大模型接入SDK—ChatSDK封装
开发语言·c++·人工智能·后端
上天_去_做颗惺星 EVE_BLUE34 分钟前
Docker高效使用指南:从基础到实战模板
开发语言·ubuntu·docker·容器·mac·虚拟环境
2401_8576835435 分钟前
C++中的原型模式
开发语言·c++·算法
s1hiyu44 分钟前
C++动态链接库开发
开发语言·c++·算法
(❁´◡`❁)Jimmy(❁´◡`❁)1 小时前
CF2188 C. Restricted Sorting
c语言·开发语言·算法
星火开发设计1 小时前
C++ 预处理指令:#include、#define 与条件编译
java·开发语言·c++·学习·算法·知识
许泽宇的技术分享1 小时前
第 1 章:认识 Claude Code
开发语言·人工智能·python
AIFQuant1 小时前
如何利用免费股票 API 构建量化交易策略:实战分享
开发语言·python·websocket·金融·restful
Hx_Ma161 小时前
SpringMVC返回值
java·开发语言·servlet