从零搭建QT(C++)开发环境到实战部署YOLOV5模型

张开发
2026/4/9 2:38:24 15 分钟阅读

分享文章

从零搭建QT(C++)开发环境到实战部署YOLOV5模型
1. 环境准备从零搭建QT开发环境第一次接触QT开发的朋友可能会被各种安装选项搞懵我刚开始配置环境时也踩过不少坑。这里分享一个经过验证的安装方案适用于大多数Linux系统以Ubuntu为例。首先需要安装基础编译工具链sudo apt update sudo apt install -y build-essential cmake git接下来安装QT的依赖库这一步很重要缺少依赖会导致后续编译出错sudo apt install -y libgl1-mesa-dev libglu1-mesa-dev freeglut3-devQT官方提供了在线安装工具Qt Maintenance Tool这是目前最方便的安装方式。下载后运行chmod x qt-unified-linux-x64-4.5.1-online.run ./qt-unified-linux-x64-4.5.1-online.run安装时建议勾选以下组件Qt 5.15.2LTS版本Qt CreatorIDEDesktop gcc 64-bit编译器Qt Charts可选数据可视化用Qt Multimedia可选音视频处理用安装完成后在终端输入qtcreator即可启动开发环境。第一次启动时建议配置下工具链进入工具-选项在Kits选项卡确认自动检测到的编译器在Qt Versions选项卡确认QT安装路径2. 创建第一个QT项目打开Qt Creator后我们来创建一个基础窗口应用。点击文件-新建文件或项目选择Application-Qt Widgets Application。项目配置有几个关键点需要注意构建系统建议选择qmake兼容性更好基类选择QMainWindow带菜单栏的标准窗口勾选Generate form自动创建UI文件创建完成后会看到项目包含这些核心文件project/ ├── project.pro # 项目配置文件 ├── main.cpp # 程序入口 ├── mainwindow.h # 主窗口头文件 ├── mainwindow.cpp # 主窗口实现 └── mainwindow.ui # 界面设计文件在mainwindow.ui中拖拽一个Label控件设置text属性为Hello World。点击运行按钮绿色三角就能看到第一个QT窗口程序了。遇到编译错误时常见问题有找不到OpenGL库安装libgl1-mesa-dev链接错误检查.pro文件中是否添加了必要的QT模块C标准不匹配在.pro中添加CONFIG c173. 集成OpenCV视觉库要在QT中使用YOLOv5需要先集成OpenCV。推荐使用v4.5版本编译时开启Qt支持git clone https://github.com/opencv/opencv.git cd opencv mkdir build cd build cmake -D WITH_QTON -D OPENCV_GENERATE_PKGCONFIGON .. make -j$(nproc) sudo make install在QT项目中集成OpenCV需要修改.pro文件# 添加OpenCV库路径 unix:!macx { INCLUDEPATH /usr/local/include/opencv4 LIBS -L/usr/local/lib -lopencv_core -lopencv_imgproc -lopencv_highgui }测试OpenCV是否正常工作#include opencv2/opencv.hpp void MainWindow::testOpenCV() { cv::Mat img cv::imread(test.jpg); cv::cvtColor(img, img, cv::COLOR_BGR2RGB); QImage qimg(img.data, img.cols, img.rows, QImage::Format_RGB888); ui-label-setPixmap(QPixmap::fromImage(qimg)); }4. 部署YOLOv5模型YOLOv5官方提供PyTorch模型我们需要先转换为ONNX格式# 在Python环境中执行 import torch model torch.hub.load(ultralytics/yolov5, yolov5s) torch.onnx.export(model, torch.randn(1,3,640,640), yolov5s.onnx)在C中加载ONNX模型需要使用ONNX Runtime。安装方法git clone --recursive https://github.com/microsoft/onnxruntime cd onnxruntime/build/Linux ./build.sh --config Release --build_shared_lib --parallelQT项目中集成ONNX Runtime的.pro配置# ONNX Runtime配置 INCLUDEPATH /path/to/onnxruntime/include LIBS -L/path/to/onnxruntime/lib -lonnxruntime创建推理引擎类class YOLOv5Detector { public: YOLOv5Detector(const std::string modelPath) { env Ort::Env(ORT_LOGGING_LEVEL_WARNING, YOLOv5); session Ort::Session(env, modelPath.c_str(), Ort::SessionOptions()); } std::vectorDetection detect(cv::Mat image) { // 预处理图像 cv::Mat blob preprocess(image); // 创建输入张量 Ort::MemoryInfo memory_info Ort::MemoryInfo::CreateCpu( OrtAllocatorType::OrtArenaAllocator, OrtMemType::OrtMemTypeDefault); Ort::Value input_tensor Ort::Value::CreateTensorfloat( memory_info, blob.ptrfloat(), blob.total(), input_shape.data(), input_shape.size()); // 执行推理 auto outputs session.Run(Ort::RunOptions{nullptr}, input_names.data(), input_tensor, 1, output_names.data(), output_names.size()); // 解析输出 return postprocess(outputs); } private: Ort::Env env; Ort::Session session; // ... 其他成员和方法 };5. 设计检测结果可视化界面在mainwindow.ui中设计以下UI元素QGraphicsView用于显示检测画面QLabel用于显示帧率信息QPushButton用于开始/停止检测实现视频检测线程class DetectionThread : public QThread { Q_OBJECT public: explicit DetectionThread(QObject *parent nullptr) : QThread(parent), isRunning(false) {} void run() override { cv::VideoCapture cap(0); // 打开摄像头 while(isRunning) { cv::Mat frame; cap frame; if(frame.empty()) continue; auto detections detector.detect(frame); emit detectionDone(frame, detections); } } void stop() { isRunning false; } signals: void detectionDone(const cv::Mat frame, const std::vectorDetection detections); private: std::atomicbool isRunning; YOLOv5Detector detector{yolov5s.onnx}; };在主窗口中连接信号槽MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui-setupUi(this); thread new DetectionThread(this); connect(thread, DetectionThread::detectionDone, this, MainWindow::updateDetectionResult); } void MainWindow::updateDetectionResult(const cv::Mat frame, const std::vectorDetection detections) { // 绘制检测框 cv::Mat result frame.clone(); for(const auto det : detections) { cv::rectangle(result, det.bbox, cv::Scalar(0,255,0), 2); cv::putText(result, det.label, cv::Point(det.bbox.x, det.bbox.y-5), cv::FONT_HERSHEY_SIMPLEX, 0.5, cv::Scalar(0,255,0), 1); } // 转换为QImage显示 QImage qimg(result.data, result.cols, result.rows, QImage::Format_RGB888); ui-graphicsView-setPixmap(QPixmap::fromImage(qimg)); }6. 性能优化技巧在实际部署中我发现几个有效的优化方法模型量化将FP32模型转为INT8速度提升2-3倍# 量化模型导出 model.fuse().eval() quantized_model torch.quantization.quantize_dynamic( model, {torch.nn.Linear}, dtypetorch.qint8) torch.onnx.export(quantized_model, torch.randn(1,3,640,640), yolov5s_int8.onnx)多线程处理使用QtConcurrent处理图像预处理QFuturecv::Mat future QtConcurrent::run([](){ return preprocessImage(frame); });GPU加速如果使用NVIDIA显卡编译带CUDA支持的OpenCV和ONNX Runtime# 编译OpenCV时添加 -D WITH_CUDAON -D CUDA_ARCH_BIN7.5 # 根据显卡算力修改内存池重用中间结果内存class MemoryPool { public: cv::Mat getMat(int rows, int cols, int type) { auto key std::make_tuple(rows, cols, type); if(pool.count(key) !pool[key].empty()) { auto mat pool[key].back(); pool[key].pop_back(); return mat; } return cv::Mat(rows, cols, type); } void returnMat(cv::Mat mat) { auto key std::make_tuple(mat.rows, mat.cols, mat.type()); pool[key].push_back(std::move(mat)); } private: std::mapstd::tupleint,int,int, std::vectorcv::Mat pool; };7. 跨平台部署方案QT的优势在于跨平台能力针对不同平台的部署需要注意Windows平台使用Visual Studio编译QT和依赖库打包时需要带上Qt5Core.dll等运行时库platforms/qwindows.dllOpenCV的DLL文件推荐使用windeployqt工具自动收集依赖嵌入式Linux交叉编译QT和OpenCV在.pro文件中指定交叉编译工具链# 树莓派示例 QMAKE_CC arm-linux-gnueabihf-gcc QMAKE_CXX arm-linux-gnueabihf-gAndroid平台安装QT的Android组件配置NDK、SDK路径在.pro中添加android { ANDROID_EXTRA_LIBS $$PWD/libs/android/libonnxruntime.so }实际部署到Jetson Nano这类边缘设备时建议使用TensorRT加速。我测试过YOLOv5s在Nano上使用TensorRT可以达到15FPS的实时性能。关键是要使用适当的输入分辨率如320x320和FP16精度。

更多文章