YOLOv8部署到C++上(综合版笔记)

小橙不吃辣椒 2024-06-13 09:05:02 阅读 63

这段时间由于项目的需要,需要将yolov8部署到C++上以及跟相应的算法结合,花了我不少时间。

现阶段有考虑过使用onnx转Tensort,但是无法输出分类的结果,故放弃,有目标检测的小伙伴可以试试,接下来使用onnxruntime来试试。

win10下 yolov8 tensorrt模型部署_tensort8.4.2.4-CSDN博客

下面我将尝试用opencv CPP推理我们得到onnx文件

参考文章

VS2019配置onnxruntime推理环境 - 知乎 (zhihu.com)

yolov8 opencv模型部署(C++版)_yolov8 c++-CSDN博客

Opencv模型部署 onnxruntime调用yolov8(C++)

方法一

这个案例可以参考

C++ OpenCV onnxruntime调用yolov8 onnx模型_哔哩哔哩_bilibili

相应源代码

百度网盘 请输入提取码

OnnxRuntime调用onnx优点

ultralytics/examples/YOLOv8-ONNXRuntime-CPP at main · ultralytics/ultralytics (github.com)

下载我们yolov8相应源代码

创建新项目

创建我们的新项目并命名,导入相应的文件

右键我们的Demo3,并选择"在文件资源管理器中打开文件夹"

复制到相应位置

右键选择包括在项目中

添加一下我们对应的引用

这里我们要选择配置我们的Release x64,下面的我是忘记改了,后面想起来了,所以下面的步骤不变。

右键我们的项目,设置我们的属性,设置语言标准为C++ 17

修改我们的安全检查,如果不修改的话,后期可能还会有错误,不修改的话我们自己也可以使用自定义宏进行处理

对应的语言模式改为默认值,如果不改的话string型改为char型的话是需要手动进行的

引入头文件

opencv(图像处理,就是我们读图然后处理图像的时候使用)

Releases - OpenCV

CUDA(使用GPU加速的时候需要使用)11.8版本

CUDA安装教程(超详细)-CSDN博客

这里我先使用的是自己先前下载的11.7版本的试试

onnxruntime 1.15.1版本

Releases · microsoft/onnxruntime (github.com)

这里我先使用自己先前的版本试试

onnxruntime-win-x64-gpu-1.17.1(之前的版本)

Releases · microsoft/onnxruntime (github.com)

添加lib引用

我们可以在我们相关的文件里找到相应的dll文件

放入我们的文件夹里

从这里C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v11.7\include

导入我们相应的文件

我们的onnxruntime跟opencv也是这样操作

添加我们的lib文件

将我们的lib文件跟include文件复制粘贴到我们的项目下

调整我们的项目路径

添加我们三个对应头文件的目录

添加我们对应的引用

./include/opencv;./include/CUDA:./include/onnxruntime;

这三个头文件我们就添加好了

我们右键生成我们的项目,发现生成失败了,再继续按照上面的视频操作,肯定哪里有问题,有成功的小伙伴

然后我们回来看到我们的主函数,这里他是要找到我们对应的标识文件,这里我们可以给他注释

这里我们使用官方的案例来做

将我们相应的文件跟图片移入

调整我们的模型文件路径

再次重新生成一下

这里我们生成失败了,可以再使用up主给的文件再试试。(步骤还是按照上面的来)

百度网盘 请输入提取码

方法二(推荐)

VS2019配置onnxruntime推理环境 - 知乎 (zhihu.com)

主要参考的文章

由于我之前部署过tensorrt的成功了

所以我猜应该是配置属性表这边出了问题

解决:error C1083: 无法打开包括文件: “opencv2/opencv.hpp”: No such file or directory-CSDN博客

严重性 代码 说明 项目 文件 行 禁止显示状态 错误 LNK2001 无法解析的外部符号 “void __cdecl cv::imshow(class std::basic_string<char,_严重性代码说明项目文件行禁止显示状态 错误lnk2001无法解析的外部符号-CSDN博客

这个是一个问题的解决方法,但是我后面把Opencv里的Lib文件换成了opencv.4.9.0的版本就没有报错了

后来发现确实是这

win10下 yolov8 tensorrt模型部署_tensort8.4.2.4-CSDN博客

VS配置属性表,保存Opencv配置信息_vs属性表-CSDN博客

可以参考这两篇文章

我们找到自己参考上面两篇文章以及配置好的属性表去重新配置

目前我成功生成的onnxruntime版本是onnxruntime-win-x64-gpu-1.17.1

opencv版本是4.9.0

期间出现了找不到opencv_490world.dll文件,我们需要将相应的两个dll文件复制粘贴至相应的文件夹下

又出现了未经处理的异常的问题

解决方法:

Opencv 未经处理的异常 Microsoft C++ 异常: cv::Exception,位于内存位置_: microsoft c++ 异常: cv::exception,位于内存位置 0x0000002-CSDN博客

这是我配置好的属性管理器

小结

最后总算成功了,但是我的检测模型的框都在左上角不知道怎么回事,知道的小伙伴可以帮我解答一下吗?

代码

main.cpp

#include <iostream>#include <iomanip>#include "inference.h" // 导入推理相关的头文件#include <filesystem>#include <fstream>#include <random>#include <regex>// 对图像进行检测void Detector(YOLO_V8*& p) { // 获取当前工作目录 std::filesystem::path current_path = std::filesystem::current_path(); // 图片所在目录为当前工作目录下的 "images" 文件夹 std::filesystem::path imgs_path = R"(D:\C++ project\Demo4\Demo4\images\data)"; // 遍历图片目录中的所有文件 for (auto& i : std::filesystem::directory_iterator(imgs_path)) { // 检查文件是否是图片文件(.jpg, .png, .jpeg) if (i.path().extension() == ".jpg" || i.path().extension() == ".png" || i.path().extension() == ".jpeg") { // 获取图片路径并读取图像 std::string img_path = i.path().string(); cv::Mat img = cv::imread(img_path); std::vector<DL_RESULT> res; // 运行推理会话以检测对象 p->RunSession(img, res); // 对每个检测到的对象进行处理 for (auto& re : res) { // 生成随机颜色 cv::RNG rng(cv::getTickCount()); cv::Scalar color(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256)); // 在图像上绘制检测框 cv::rectangle(img, re.box, color, 3); // 格式化置信度并生成标签 float confidence = floor(100 * re.confidence) / 100; std::cout << std::fixed << std::setprecision(2); std::string label = p->classes[re.classId] + " " + std::to_string(confidence).substr(0, std::to_string(confidence).size() - 4); // 在图像上绘制标签 cv::rectangle( img, cv::Point(re.box.x, re.box.y - 25), cv::Point(re.box.x + label.length() * 15, re.box.y), color, cv::FILLED ); cv::putText( img, label, cv::Point(re.box.x, re.box.y - 5), cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0, 0, 0), 2 ); } // 显示结果并等待用户按下任意键 std::cout << "Press any key to exit" << std::endl; cv::imshow("Result of Detection", img); cv::waitKey(0); cv::destroyAllWindows(); } }}// 对图像进行分类void Classifier(YOLO_V8*& p){ // 获取当前工作目录 std::filesystem::path current_path = std::filesystem::current_path(); // 设置要访问的图片目录路径 std::filesystem::path imgs_path = R"(D:\C++ project\Demo4\Demo4\images\person)"; // 设置类别名称 p->classes = { "person", "normal" }; // 生成随机数引擎 std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dis(0, 255); // 遍历图片目录中的所有文件 for (auto& i : std::filesystem::directory_iterator(imgs_path)) { // 检查文件是否是图片文件(.jpg, .png) if (i.path().extension() == ".jpg" || i.path().extension() == ".png") { // 获取图片路径并读取图像 std::string img_path = i.path().string(); cv::Mat img = cv::imread(img_path); std::vector<DL_RESULT> res; // 运行推理会话以进行图像分类 char* ret = p->RunSession(img, res); // 绘制分类结果 float positionY = 50; for (int i = 0; i < res.size(); i++) { // 生成随机颜色 int r = dis(gen); int g = dis(gen); int b = dis(gen); // 获取类别名称和置信度 std::string label; if (res[i].classId >= 0 && res[i].classId < p->classes.size()) { label = p->classes[res[i].classId] + ": " + std::to_string(res[i].confidence); } else { label = "Unknown"; } // 在图像上绘制分类标签和置信度 cv::putText(img, label, cv::Point(10, positionY), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(b, g, r), 2); positionY += 50; } // 在窗口中显示分类结果并等待用户按下任意键 cv::imshow("TEST_CLS", img); cv::waitKey(0); cv::destroyAllWindows(); // 可选:保存分类结果图像 //cv::imwrite("E:\\output\\" + std::to_string(k) + ".png", img); } }}// 读取数据集的标签//int ReadCoCoYaml(YOLO_V8*& p) {// // 打开YAML文件// std::ifstream file("D:\\project\\yolov8_main\\ultralytics\\coco.yaml");// if (!file.is_open())// {// // 如果打开文件失败,则输出错误信息// std::cerr << "Failed to open file" << std::endl;// return 1;// }//// // 逐行读取文件内容// std::string line;// std::vector<std::string> lines;// while (std::getline(file, line))// {// lines.push_back(line);// }//// // 查找类别名称部分的起始和结束位置// std::size_t start = 0;// std::size_t end = 0;// for (std::size_t i = 0; i < lines.size(); i++)// {// if (lines[i].find("names:") != std::string::npos)// {// start = i + 1;// }// else if (start > 0 && lines[i].empty())// {// end = i;// break;// }// }//// // 提取类别名称// std::vector<std::string> names;// for (std::size_t i = start; i < end; i++)// {// // 解析类别名称键值对// std::size_t colon_pos = lines[i].find(':');// if (colon_pos != std::string::npos)// {// std::string name = lines[i].substr(colon_pos + 1);// // 去除字符串两端的空格// name = std::regex_replace(name, std::regex("^ +| +$|( ) +"), "$1");// names.push_back(name);// }// }//// // 将类别名称赋值给YOLO_V8对象// p->classes = names;// return 0;//}// 进行检测测试void DetectTest(){#define USE_CUDA // 创建YOLO_V8对象指针 YOLO_V8* yoloDetector = new YOLO_V8; // 初始化推理参数 DL_INIT_PARAM params; params.rectConfidenceThreshold = 0.1; params.iouThreshold = 0.5; params.modelPath = "./models/yolov8n.onnx"; params.imgSize = { 640, 640 }; // 设置检测类别为"person" yoloDetector->classes = { "person" };#ifdef USE_CUDA // 如果使用CUDA加速 params.cudaEnable = true; // 使用GPU FP32推理 params.modelType = YOLO_DETECT_V8; // 使用GPU FP16推理(注意:需要修改FP16的ONNX模型) //params.modelType = YOLO_DETECT_V8_HALF;#else // 如果不使用CUDA,即使用CPU推理 params.modelType = YOLO_DETECT_V8; params.cudaEnable = false;#endif // 创建推理会话 yoloDetector->CreateSession(params); // 执行检测函数 Detector(yoloDetector);}// 进行分类测试void ClsTest(){ // 创建YOLO_V8对象指针 YOLO_V8* yoloDetector = new YOLO_V8; // 设置分类模型路径 std::string model_path = "./models/yolov8s-cls.onnx"; // 读取COCO数据集标签 /*ReadMuckYaml(yoloDetector);*/ // 初始化推理参数 DL_INIT_PARAM params{ model_path, YOLO_CLS, {224, 224} }; // 创建推理会话 yoloDetector->CreateSession(params); // 执行分类函数 Classifier(yoloDetector);}// 主函数int main(){ // 执行检测测试 ClsTest(); // 执行分类测试 //ClsTest();}

这里我把读取数据集标签注释掉了,因为我觉得直接输入分类更简单,就不用编译了

inference.h

#pragma once#define RET_OK nullptr#ifdef _WIN32#include <Windows.h>#include <direct.h>#include <io.h>#endif#include <string>#include <vector>#include <cstdio>#include <opencv2/opencv.hpp>#include "onnxruntime_cxx_api.h"#ifdef USE_CUDA#include <cuda_fp16.h>#endifenum MODEL_TYPE{ //FLOAT32 MODEL YOLO_DETECT_V8 = 1, YOLO_POSE = 2, YOLO_CLS = 3, //FLOAT16 MODEL YOLO_DETECT_V8_HALF = 4, YOLO_POSE_V8_HALF = 5,};typedef struct _DL_INIT_PARAM{ std::string modelPath; MODEL_TYPE modelType = YOLO_DETECT_V8; std::vector<int> imgSize = { 640, 640 }; float rectConfidenceThreshold = 0.6; float iouThreshold = 0.5; intkeyPointsNum = 2;//Note:kpt number for pose bool cudaEnable = false; int logSeverityLevel = 3; int intraOpNumThreads = 1;} DL_INIT_PARAM;typedef struct _DL_RESULT{ int classId; float confidence; cv::Rect box; std::vector<cv::Point2f> keyPoints;} DL_RESULT;class YOLO_V8{public: YOLO_V8(); ~YOLO_V8();public: char* CreateSession(DL_INIT_PARAM& iParams); char* RunSession(cv::Mat& iImg, std::vector<DL_RESULT>& oResult); char* WarmUpSession(); template<typename N> char* TensorProcess(clock_t& starttime_1, cv::Mat& iImg, N& blob, std::vector<int64_t>& inputNodeDims, std::vector<DL_RESULT>& oResult); char* PreProcess(cv::Mat& iImg, std::vector<int> iImgSize, cv::Mat& oImg); std::vector<std::string> classes{};private: Ort::Env env; Ort::Session* session; bool cudaEnable; Ort::RunOptions options; std::vector<const char*> inputNodeNames; std::vector<const char*> outputNodeNames; MODEL_TYPE modelType; std::vector<int> imgSize; float rectConfidenceThreshold; float iouThreshold; float resizeScales;//letterbox scale};

inference.cpp

#include "inference.h"#include <regex>#define benchmark#define min(a,b) (((a) < (b)) ? (a) : (b))YOLO_V8::YOLO_V8() {}YOLO_V8::~YOLO_V8() { delete session;}#ifdef USE_CUDAnamespace Ort{ template<> struct TypeToTensorType<half> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; };}#endiftemplate<typename T>char* BlobFromImage(cv::Mat& iImg, T& iBlob) { int channels = iImg.channels(); int imgHeight = iImg.rows; int imgWidth = iImg.cols; for (int c = 0; c < channels; c++) { for (int h = 0; h < imgHeight; h++) { for (int w = 0; w < imgWidth; w++) { iBlob[c * imgWidth * imgHeight + h * imgWidth + w] = typename std::remove_pointer<T>::type( (iImg.at<cv::Vec3b>(h, w)[c]) / 255.0f); } } } return RET_OK;}char* YOLO_V8::PreProcess(cv::Mat& iImg, std::vector<int> iImgSize, cv::Mat& oImg){ if (iImg.channels() == 3) { oImg = iImg.clone(); cv::cvtColor(oImg, oImg, cv::COLOR_BGR2RGB); } else { cv::cvtColor(iImg, oImg, cv::COLOR_GRAY2RGB); } switch (modelType) { case YOLO_DETECT_V8: case YOLO_POSE: case YOLO_DETECT_V8_HALF: case YOLO_POSE_V8_HALF://LetterBox { if (iImg.cols >= iImg.rows) { resizeScales = iImg.cols / (float)iImgSize.at(0); cv::resize(oImg, oImg, cv::Size(iImgSize.at(0), int(iImg.rows / resizeScales))); } else { resizeScales = iImg.rows / (float)iImgSize.at(0); cv::resize(oImg, oImg, cv::Size(int(iImg.cols / resizeScales), iImgSize.at(1))); } cv::Mat tempImg = cv::Mat::zeros(iImgSize.at(0), iImgSize.at(1), CV_8UC3); oImg.copyTo(tempImg(cv::Rect(0, 0, oImg.cols, oImg.rows))); oImg = tempImg; break; } case YOLO_CLS://CenterCrop { int h = iImg.rows; int w = iImg.cols; int m = min(h, w); int top = (h - m) / 2; int left = (w - m) / 2; cv::resize(oImg(cv::Rect(left, top, m, m)), oImg, cv::Size(iImgSize.at(0), iImgSize.at(1))); break; } } return RET_OK;}char* YOLO_V8::CreateSession(DL_INIT_PARAM& iParams) { char* Ret = RET_OK; std::regex pattern("[\u4e00-\u9fa5]"); bool result = std::regex_search(iParams.modelPath, pattern); if (result) { Ret = "[YOLO_V8]:Your model path is error.Change your model path without chinese characters."; std::cout << Ret << std::endl; return Ret; } try { rectConfidenceThreshold = iParams.rectConfidenceThreshold; iouThreshold = iParams.iouThreshold; imgSize = iParams.imgSize; modelType = iParams.modelType; env = Ort::Env(ORT_LOGGING_LEVEL_WARNING, "Yolo"); Ort::SessionOptions sessionOption; if (iParams.cudaEnable) { cudaEnable = iParams.cudaEnable; OrtCUDAProviderOptions cudaOption; cudaOption.device_id = 0; sessionOption.AppendExecutionProvider_CUDA(cudaOption); } sessionOption.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL); sessionOption.SetIntraOpNumThreads(iParams.intraOpNumThreads); sessionOption.SetLogSeverityLevel(iParams.logSeverityLevel);#ifdef _WIN32 int ModelPathSize = MultiByteToWideChar(CP_UTF8, 0, iParams.modelPath.c_str(), static_cast<int>(iParams.modelPath.length()), nullptr, 0); wchar_t* wide_cstr = new wchar_t[ModelPathSize + 1]; MultiByteToWideChar(CP_UTF8, 0, iParams.modelPath.c_str(), static_cast<int>(iParams.modelPath.length()), wide_cstr, ModelPathSize); wide_cstr[ModelPathSize] = L'\0'; const wchar_t* modelPath = wide_cstr;#else const char* modelPath = iParams.modelPath.c_str();#endif // _WIN32 session = new Ort::Session(env, modelPath, sessionOption); Ort::AllocatorWithDefaultOptions allocator; size_t inputNodesNum = session->GetInputCount(); for (size_t i = 0; i < inputNodesNum; i++) { Ort::AllocatedStringPtr input_node_name = session->GetInputNameAllocated(i, allocator); char* temp_buf = new char[50]; strcpy(temp_buf, input_node_name.get()); inputNodeNames.push_back(temp_buf); } size_t OutputNodesNum = session->GetOutputCount(); for (size_t i = 0; i < OutputNodesNum; i++) { Ort::AllocatedStringPtr output_node_name = session->GetOutputNameAllocated(i, allocator); char* temp_buf = new char[10]; strcpy(temp_buf, output_node_name.get()); outputNodeNames.push_back(temp_buf); } options = Ort::RunOptions{ nullptr }; WarmUpSession(); return RET_OK; } catch (const std::exception& e) { const char* str1 = "[YOLO_V8]:"; const char* str2 = e.what(); std::string result = std::string(str1) + std::string(str2); char* merged = new char[result.length() + 1]; std::strcpy(merged, result.c_str()); std::cout << merged << std::endl; delete[] merged; return "[YOLO_V8]:Create session failed."; }}char* YOLO_V8::RunSession(cv::Mat& iImg, std::vector<DL_RESULT>& oResult) {#ifdef benchmark clock_t starttime_1 = clock();#endif // benchmark char* Ret = RET_OK; cv::Mat processedImg; PreProcess(iImg, imgSize, processedImg); if (modelType < 4) { float* blob = new float[processedImg.total() * 3]; BlobFromImage(processedImg, blob); std::vector<int64_t> inputNodeDims = { 1, 3, imgSize.at(0), imgSize.at(1) }; TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult); } else {#ifdef USE_CUDA half* blob = new half[processedImg.total() * 3]; BlobFromImage(processedImg, blob); std::vector<int64_t> inputNodeDims = { 1,3,imgSize.at(0),imgSize.at(1) }; TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult);#endif } return Ret;}template<typename N>char* YOLO_V8::TensorProcess(clock_t& starttime_1, cv::Mat& iImg, N& blob, std::vector<int64_t>& inputNodeDims, std::vector<DL_RESULT>& oResult) { Ort::Value inputTensor = Ort::Value::CreateTensor<typename std::remove_pointer<N>::type>( Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1), inputNodeDims.data(), inputNodeDims.size());#ifdef benchmark clock_t starttime_2 = clock();#endif // benchmark auto outputTensor = session->Run(options, inputNodeNames.data(), &inputTensor, 1, outputNodeNames.data(), outputNodeNames.size());#ifdef benchmark clock_t starttime_3 = clock();#endif // benchmark Ort::TypeInfo typeInfo = outputTensor.front().GetTypeInfo(); auto tensor_info = typeInfo.GetTensorTypeAndShapeInfo(); std::vector<int64_t> outputNodeDims = tensor_info.GetShape(); auto output = outputTensor.front().GetTensorMutableData<typename std::remove_pointer<N>::type>(); delete[] blob; switch (modelType) { case YOLO_DETECT_V8: case YOLO_DETECT_V8_HALF: { int strideNum = outputNodeDims[1];//8400 int signalResultNum = outputNodeDims[2];//84 std::vector<int> class_ids; std::vector<float> confidences; std::vector<cv::Rect> boxes; cv::Mat rawData; if (modelType == YOLO_DETECT_V8) { // FP32 rawData = cv::Mat(strideNum, signalResultNum, CV_32F, output); } else { // FP16 rawData = cv::Mat(strideNum, signalResultNum, CV_16F, output); rawData.convertTo(rawData, CV_32F); } //Note: //ultralytics add transpose operator to the output of yolov8 model.which make yolov8/v5/v7 has same shape //https://github.com/ultralytics/assets/releases/download/v8.1.0/yolov8n.pt //rowData = rowData.t(); float* data = (float*)rawData.data; for (int i = 0; i < strideNum; ++i) { float* classesScores = data + 4; cv::Mat scores(1, this->classes.size(), CV_32FC1, classesScores); cv::Point class_id; double maxClassScore; cv::minMaxLoc(scores, 0, &maxClassScore, 0, &class_id); if (maxClassScore > rectConfidenceThreshold) { confidences.push_back(maxClassScore); class_ids.push_back(class_id.x); float x = data[0]; float y = data[1]; float w = data[2]; float h = data[3]; int left = int((x - 0.5 * w) * resizeScales); int top = int((y - 0.5 * h) * resizeScales); int width = int(w * resizeScales); int height = int(h * resizeScales); boxes.push_back(cv::Rect(left, top, width, height)); } data += signalResultNum; } std::vector<int> nmsResult; cv::dnn::NMSBoxes(boxes, confidences, rectConfidenceThreshold, iouThreshold, nmsResult); for (int i = 0; i < nmsResult.size(); ++i) { int idx = nmsResult[i]; DL_RESULT result; result.classId = class_ids[idx]; result.confidence = confidences[idx]; result.box = boxes[idx]; oResult.push_back(result); }#ifdef benchmark clock_t starttime_4 = clock(); double pre_process_time = (double)(starttime_2 - starttime_1) / CLOCKS_PER_SEC * 1000; double process_time = (double)(starttime_3 - starttime_2) / CLOCKS_PER_SEC * 1000; double post_process_time = (double)(starttime_4 - starttime_3) / CLOCKS_PER_SEC * 1000; if (cudaEnable) { std::cout << "[YOLO_V8(CUDA)]: " << pre_process_time << "ms pre-process, " << process_time << "ms inference, " << post_process_time << "ms post-process." << std::endl; } else { std::cout << "[YOLO_V8(CPU)]: " << pre_process_time << "ms pre-process, " << process_time << "ms inference, " << post_process_time << "ms post-process." << std::endl; }#endif // benchmark break; } case YOLO_CLS: { DL_RESULT result; for (int i = 0; i < this->classes.size(); i++) { result.classId = i; result.confidence = output[i]; oResult.push_back(result); } break; } default: std::cout << "[YOLO_V8]: " << "Not support model type." << std::endl; } return RET_OK;}char* YOLO_V8::WarmUpSession() { clock_t starttime_1 = clock(); cv::Mat iImg = cv::Mat(cv::Size(imgSize.at(0), imgSize.at(1)), CV_8UC3); cv::Mat processedImg; PreProcess(iImg, imgSize, processedImg); if (modelType < 4) { float* blob = new float[iImg.total() * 3]; BlobFromImage(processedImg, blob); std::vector<int64_t> YOLO_input_node_dims = { 1, 3, imgSize.at(0), imgSize.at(1) }; Ort::Value input_tensor = Ort::Value::CreateTensor<float>( Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1), YOLO_input_node_dims.data(), YOLO_input_node_dims.size()); auto output_tensors = session->Run(options, inputNodeNames.data(), &input_tensor, 1, outputNodeNames.data(), outputNodeNames.size()); delete[] blob; clock_t starttime_4 = clock(); double post_process_time = (double)(starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000; if (cudaEnable) { std::cout << "[YOLO_V8(CUDA)]: " << "Cuda warm-up cost " << post_process_time << " ms. " << std::endl; } } else {#ifdef USE_CUDA half* blob = new half[iImg.total() * 3]; BlobFromImage(processedImg, blob); std::vector<int64_t> YOLO_input_node_dims = { 1,3,imgSize.at(0),imgSize.at(1) }; Ort::Value input_tensor = Ort::Value::CreateTensor<half>(Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1), YOLO_input_node_dims.data(), YOLO_input_node_dims.size()); auto output_tensors = session->Run(options, inputNodeNames.data(), &input_tensor, 1, outputNodeNames.data(), outputNodeNames.size()); delete[] blob; clock_t starttime_4 = clock(); double post_process_time = (double)(starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000; if (cudaEnable) { std::cout << "[YOLO_V8(CUDA)]: " << "Cuda warm-up cost " << post_process_time << " ms. " << std::endl; }#endif } return RET_OK;}



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。