win下C++通过Clion部署yolov5——libtorch+yolov5

一、环境配置

需要配置libtorch+OpenCV,此处参考博文:clion配置libtorch+OpenCV环境配置

环境解决后即可开始下一步啦。

二、下载官网例子

下载地址:YOLOv5 libtorch版本测试代码

解压后如图所示:
在这里插入图片描述

三、测试

3.1、创建项目

博主是新建了一个项目,把相关代码复制过去重新运行的。
在这里插入图片描述
这是总的目录结构。
其中【images】和【weights】即为二中下载源码中的【images】和【weights】,其他的头文件和源文件是二中源码在这里插入图片描述
这里博主没有新建【include】和【src】目录,直接将5个文件复制到了新建项目下。

3.2、cmakelist.txt编写

这一步至关重要。

cmakelist.txt如下:

cmake_minimum_required(VERSION 3.19)
project(ModelDeploy)

set(CMAKE_CXX_STANDARD 14)

set(CMAKE_PREFIX_PATH D:/pyTorch/libtorch-win-shared-with-deps-2.0.0+cu117/libtorch)
#set(Torch_DIR "D:/pyTorch/libtorch-win-shared-with-deps-2.0.0+cu117/libtorch/share/cmake/Torch")
#include_directories(D:/pyTorch/libtorch-win-shared-with-deps-2.0.0+cu117/libtorch/include")
#include_directories("D:/pyTorch/libtorch-win-shared-with-deps-2.0.0+cu117/libtorch/include/torch/csrc/api/include")
find_package(Torch REQUIRED )

set(OpenCV_DIR D:/opencv/opencv-4.5.5/cmake-build-release-visual-studio/install)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})

add_executable(modelDeploy main.cpp detector.cpp utils.h cxxopts.hpp)
target_link_libraries(modelDeploy ${TORCH_LIBRARIES} ${OpenCV_LIBS})
set_property(TARGET modelDeploy PROPERTY CXX_STANDARD 14)

其实就是博文clion配置libtorch+OpenCV环境配置中的cmakelist.txt做了些许修改。

在这里插入图片描述

其中红色框和绿色框分别是libtorch和OpenCV的相关配置;蓝色框则是添加需要运行的头文件和源文件,这里就是和博文clion配置libtorch+OpenCV环境配置中的cmakelist.txt的不同之处,所以关于红色框和绿色框的路径地址怎么给,也可以参考该博文。

3.3、运行测试

main.cpp

#include <iostream>
#include <torch/script.h>
#include <memory>
#include <torch/torch.h>

#include <iostream>
#include <time.h>
#include<windows.h>

#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include "detector.h"
#include "cxxopts.hpp"

using namespace cv;

std::vector<std::string> LoadNames(const std::string& path)
{
    // load class names
    std::vector<std::string> class_names;
    std::ifstream infile(path);
    if (infile.is_open()) {
        std::string line;
        while (std::getline(infile, line)) {
            class_names.emplace_back(line);
        }
        infile.close();
    }
    else {
        std::cerr << "Error loading the class names!\n";
    }

    return class_names;
}
void Demo(cv::Mat& img,
          const std::vector<std::vector<Detection>>& detections,
          const std::vector<std::string>& class_names,
          bool label = true) {

    if (!detections.empty()) {
        for (const auto& detection : detections[0]) {
            const auto& box = detection.bbox;
            float score = detection.score;
            int class_idx = detection.class_idx;

            cv::rectangle(img, box, cv::Scalar(0, 0, 255), 2);

            if (label) {
                std::stringstream ss;
                ss << std::fixed << std::setprecision(2) << score;
                std::string s = class_names[class_idx] + " " + ss.str();

                auto font_face = cv::FONT_HERSHEY_DUPLEX;
                auto font_scale = 1.0;
                int thickness = 1;
                int baseline=0;
                auto s_size = cv::getTextSize(s, font_face, font_scale, thickness, &baseline);
                cv::rectangle(img,
                              cv::Point(box.tl().x, box.tl().y - s_size.height - 5),
                              cv::Point(box.tl().x + s_size.width, box.tl().y),
                              cv::Scalar(0, 0, 255), -1);
                cv::putText(img, s, cv::Point(box.tl().x, box.tl().y - 5),
                            font_face , font_scale, cv::Scalar(255, 255, 255), thickness);
            }
        }
    }

    cv::namedWindow("Result", cv::WINDOW_AUTOSIZE);
    cv::imshow("Result", img);
    cv::waitKey(0);
}

int main(int argc, const char* argv[]) {
  /*  std::cout << "Hello world." << std::endl;
    torch::Tensor a = torch::rand({2, 3});
    std::cout << a << std::endl;
    std::string path = "D:/aniya.jpg";
    Mat im = imread(path);
    imshow("image", im);
    waitKey(0);

    torch::jit::script::Module module;
    std::cout << torch::cuda::is_available() << std::endl;
    try {
        module = torch::jit::load("D:/MCworkspace/ModelDeploy/yolov5s.torchscript.pt");
        module.to(torch::kCUDA);		// set model to cpu / cuda mode
        module.eval();
        std::cout << "MODEL LOADED\n";
    }
    catch (const c10::Error& e) {
        std::cerr << "error loading the model\n";
    }
*/
    cxxopts::Options parser(argv[0], "A LibTorch inference implementation of the yolov5");
    // TODO: add other args
    parser.allow_unrecognised_options().add_options()
            ("weights", "yolov5s.torchscript.pt", cxxopts::value<std::string>()->default_value("../weights/yolov5s.torchscript.pt"))
            ("source", "images", cxxopts::value<std::string>()->default_value("../images/bus.jpg"))
            ("conf-thres", "object confidence threshold", cxxopts::value<float>()->default_value("0.4"))
            ("iou-thres", "IOU threshold for NMS", cxxopts::value<float>()->default_value("0.5"))
            ("gpu", "Enable cuda device or cpu", cxxopts::value<bool>()->default_value("false"))
            ("view-img", "display results", cxxopts::value<bool>()->default_value("true"))
            ("h,help", "Print usage");

    auto opt = parser.parse(argc, argv);

    if (opt.count("help")) {
        std::cout << parser.help() << std::endl;
        exit(0);
    }

    // check if gpu flag is set
    bool is_gpu = opt["gpu"].as<bool>();

    // set device type - CPU/GPU
    torch::DeviceType device_type;
    if (torch::cuda::is_available() && is_gpu) {
        device_type = torch::kCUDA;
    } else {
        device_type = torch::kCPU;
    }

    // load class names from dataset for visualization
    std::vector<std::string> class_names = LoadNames("../weights/coco.names");
    if (class_names.empty()) {
        return -1;
    }

    // load network
    std::string weights = opt["weights"].as<std::string>();
    auto detector = Detector(weights, device_type);

    // load input image
    std::string source = opt["source"].as<std::string>();
    cv::Mat img = cv::imread(source);
    if (img.empty()) {
        std::cerr << "Error loading the image!\n";
        return -1;
    }

    // run once to warm up
    std::cout << "Run once on empty image" << std::endl;
    auto temp_img = cv::Mat::zeros(img.rows, img.cols, CV_32FC3);
    detector.Run(temp_img, 1.0f, 1.0f);

    // set up threshold
    float conf_thres = opt["conf-thres"].as<float>();
    float iou_thres = opt["iou-thres"].as<float>();

    // inference
    auto result = detector.Run(img, conf_thres, iou_thres);

    // visualize detections
    if (opt["view-img"].as<bool>()) {
        Demo(img, result, class_names);
    }

//    cv::destroyAllWindows();
//    Sleep(100000);
//    waitKey(0);

    return 0;

}

这里可以先在clion编辑器端运行,所以博主在源码的基础上添加了两个默认值,可以直接运行:

在这里插入图片描述
在这里插入图片描述

终端运行

进入到生成的.exe可执行文件目录,也就是编译目录下:
在这里插入图片描述
在运行之前,需要将【images】复制到编译目录下,这是方便自定义给测试图片时路径书写方便。
运行modelDeploy.exe:

modelDeploy.exe --source ../images/bus.jpg --view-img

在这里插入图片描述

如果不自定义图片,直接运行modelDeploy.exe,效果则和编译器端直接运行的结果一样
在这里插入图片描述
对于终端会闪退的问题,可以添加如下代码解决。

#include<windows.h>
Sleep(100000);

代码Sleep(100000)的时间可以自行设置。

至此就结束啦。部署有什么问题可以私信博主。

<think>好的,我现在需要帮助用户在CLion中配置Qt6和C++使用MSVC编译器。首先,我得回忆一下之前用户提供的引用内容,看看有哪些信息可以利用。引用[1]、[2]、[3]、[4]都提到了CLion配置Qt和MSVC的相关步骤,可能有一些共同的步骤可以参考。 首先,用户提到要使用Qt6和MSVC编译器。根据引用[1],安装Qt时需要注意选择MSVC2017或更高版本的组件,比如Qt5.12.12用的是MSVC2017。现在用户要升级到Qt6,可能需要对应更高版本的MSVC,比如MSVC2019或2022,所以需要确认Qt6支持的MSVC版本。然后,用户需要安装Visual Studio,因为MSVC编译器需要VS的构建工具,引用[2]和[3]都提到了这一点。可能用户需要安装VS2019或更高版本,并确保安装了C++桌面开发工作负载。 接下来,配置Qt Creator中的编译器设置,如引用[1]所述,需要在Qt Creator中配置MSVC编译器,并添加到Kits中。但用户是要在CLion中使用,所以可能需要确保CLion能够识别这些编译器。引用[2]提到在CLion中配置Qt和MSVC需要设置工具链,选择Visual Studio作为工具链,并指定环境变量。这里可能需要用户在CLion的Settings里设置正确的工具链路径,比如选择VS的vcvarsall.bat路径。 然后,配置CMakeLists.txt。引用[3]提供了添加编译选项的示例,特别是处理MSVC的编码警告问题。用户需要在CMakeLists中添加add_compile_options来设置utf-8编码,避免中文路径或代码导致的警告。此外,需要正确链接Qt的库,通过find_package(Qt6)和target_link_libraries来引入必要的模块。 可能还需要注意环境变量的问题,比如在CLion中启动时是否加载了VS的环境变量。引用[2]提到可能需要手动加载环境变量或者在CLion的配置中指定。另外,构建配置中选择正确的生成器,比如Ninja或Visual Studio,可能需要根据实际情况调整。 用户的问题可能遇到的常见错误包括编译器找不到Qt模块、链接错误或者编码问题。例如,引用[4]提到MinGW和MSVC在使用OpenCV时的不同配置方法,但这里换成Qt6,可能需要正确设置包含路径和库路径。此外,如果使用的Qt6是MSVC版本,必须确保CLion使用的是对应的MSVC工具链,而不是MinGW。 最后,测试配置是否成功,创建一个简单的Qt项目,构建并运行。如果出现错误,检查CMakeLists是否正确,编译器是否匹配,环境变量是否设置正确。可能需要参考引用中的步骤逐步排查,比如确认Qt安装路径是否正确,MSVC工具链是否有效,以及编码选项是否添加。</think>### 逐步配置 CLion 使用 Qt6 和 MSVC 编译器 #### **1. 安装必要软件** - **Visual Studio 2019/2022** 安装时勾选 **"使用C++的桌面开发"** 工作负载,确保包含 **MSVC编译器** 和 **Windows SDK** [^1][^2]。 - **Qt6 MSVC 版本** 在 [Qt 官网](https://www.qt.io/download) 下载在线安装程序,选择 **Qt 6.x.x (MSVC 20xx 64-bit)** 组件(例如 `Qt 6.5.0 MSVC2019 64-bit`)。 - **CLion 2023.x 或更新版本** 确保支持最新的 CMake 和 Qt 工具链。 --- #### **2. 配置 MSVC 工具链** 1. 打开 CLion → **File → Settings → Build, Execution, Deployment → Toolchains**。 2. 点击 **+** 添加新工具链 → 选择 **Visual Studio** 类型。 3. 在 **Architecture** 中选择 **amd64**(64位架构),路径自动检测或手动指定 `vcvarsall.bat`(默认路径为 `C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvarsall.bat`)[^2][^3]。 4. 点击 **Apply** 保存配置。 --- #### **3. 配置 Qt6 路径** 1. 打开 CLion → **File → Settings → Build, Execution, Deployment → CMake**。 2. 在 **Environment** 中添加 Qt6 根目录的环境变量(例如 `Qt6_DIR=C:\Qt\6.5.0\msvc2019_64`)[^2]。 3. 在 **CMake options** 中添加路径声明: ```cmake -DCMAKE_PREFIX_PATH="C:/Qt/6.5.0/msvc2019_64/lib/cmake" ``` --- #### **4. 配置 CMakeLists.txt** 在项目根目录的 `CMakeLists.txt` 中添加以下内容: ```cmake cmake_minimum_required(VERSION 3.25) project(MyQtApp) # 设置编码(解决MSVC中文警告) if(MSVC) add_compile_options("$<$<C_COMPILER_ID:MSVC>:/utf-8>") add_compile_options("$<$<CXX_COMPILER_ID:MSVC>:/utf-8>") endif() # 查找Qt6库 find_package(Qt6 REQUIRED COMPONENTS Core Widgets) # 添加可执行文件 add_executable(MyApp main.cpp) # 链接Qt库 target_link_libraries(MyApp PRIVATE Qt6::Core Qt6::Widgets) ``` --- #### **5. 验证配置** 1. 创建简单的 Qt 窗口程序(例如 `main.cpp`): ```cpp #include <QApplication> #include <QLabel> int main(int argc, char *argv[]) { QApplication app(argc, argv); QLabel label("Hello Qt6 with MSVC!"); label.show(); return app.exec(); } ``` 2. 点击 **Build → Build Project**,确认无编译错误。 3. 运行程序,检查窗口是否正常显示。 --- #### **常见问题解决** - **错误:找不到 Qt6 模块** 检查 `CMAKE_PREFIX_PATH` 是否指向正确的 Qt6 CMake 目录[^1]。 - **MSVC 编码警告** 确保 `CMakeLists.txt` 中添加了 `/utf-8` 编译选项[^3]。 - **调试器无法启动** 在 CLion 的 **Run/Debug Configurations** 中,选择 **Visual Studio** 作为调试器类型。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我宿孤栈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值