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();
}
相关推荐
shoubepatien39 分钟前
JAVA -- 05
java·开发语言
寰天柚子39 分钟前
Java并发编程中的线程安全问题与解决方案全解析
java·开发语言·python
沐知全栈开发42 分钟前
Bootstrap 下拉菜单:设计与实现指南
开发语言
Evand J1 小时前
【MATLAB例程】多锚点RSSI定位和基站选择方法,基于GDOP、基站距离等因素。以Wi-Fi定位为例,附下载链接
开发语言·matlab·定位·gdop·rssi
superman超哥1 小时前
仓颉语言中锁的实现机制深度剖析与并发实践
c语言·开发语言·c++·python·仓颉
JAVA+C语言1 小时前
String Constant Pool
java·开发语言
郝学胜-神的一滴1 小时前
OpenGL的glDrawElements函数详解
开发语言·c++·程序人生·游戏·图形渲染
moxiaoran57532 小时前
Go语言结构体
开发语言·后端·golang
wearegogog1232 小时前
基于C# WinForm实现的带条码打印的固定资产管理
开发语言·c#
Lvan的前端笔记2 小时前
python:深入理解 Python 的 `__name__ == “__main__“` 与双下划线(dunder)机制
开发语言·python