当前位置:   article > 正文

Qt使用opencv打开摄像头

Qt使用opencv打开摄像头

1.效果图

2.代码

  1. #include "widget.h"
  2. #include <QApplication>
  3. #include <opencv2/core/core.hpp>
  4. #include <opencv2/highgui/highgui.hpp>
  5. #include <opencv2/imgproc/imgproc.hpp>
  6. #include <QImage>
  7. #include <QLabel>
  8. #include <QTimer>
  9. #include <opencv2/opencv.hpp>
  10. using namespace cv;
  11. int main(int argc, char *argv[])
  12. {
  13. QApplication a(argc, argv);
  14. // 创建一个 QLabel 用于显示图像
  15. QLabel label;
  16. label.resize(640, 480); // 可根据需要进行调整
  17. label.show();
  18. // 打开摄像头
  19. cv::VideoCapture capture(0);
  20. if (!capture.isOpened()) {
  21. qDebug("Failed to open camera.");
  22. return -1;
  23. }
  24. // 使用 QTimer 定期更新图像显示
  25. QTimer timer;
  26. QObject::connect(&timer, &QTimer::timeout, [&]() {
  27. cv::Mat frame;
  28. capture >> frame; // 获取一帧图像
  29. if (!frame.empty()) {
  30. // 将 OpenCV 的图像转换为 Qt 的 QImage
  31. QImage image(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888);
  32. image = image.rgbSwapped(); // BGR 转 RGB
  33. // 将 QImage 设置到 QLabel 上显示
  34. label.setPixmap(QPixmap::fromImage(image).scaled(label.size(), Qt::KeepAspectRatio));
  35. }
  36. });
  37. // 每秒更新一次图像显示
  38. timer.start(1000 / 30); // 30 fps
  39. return a.exec();
  40. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/344968
推荐阅读
相关标签
  

闽ICP备14008679号