当前位置:   article > 正文

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

yolov8 c++

这段时间由于项目的需要,需要将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
  1. #include <iostream>
  2. #include <iomanip>
  3. #include "inference.h" // 导入推理相关的头文件
  4. #include <filesystem>
  5. #include <fstream>
  6. #include <random>
  7. #include <regex>
  8. // 对图像进行检测
  9. void Detector(YOLO_V8*& p) {
  10. // 获取当前工作目录
  11. std::filesystem::path current_path = std::filesystem::current_path();
  12. // 图片所在目录为当前工作目录下的 "images" 文件夹
  13. std::filesystem::path imgs_path = R"(D:\C++ project\Demo4\Demo4\images\data)";
  14. // 遍历图片目录中的所有文件
  15. for (auto& i : std::filesystem::directory_iterator(imgs_path))
  16. {
  17. // 检查文件是否是图片文件(.jpg, .png, .jpeg)
  18. if (i.path().extension() == ".jpg" || i.path().extension() == ".png" || i.path().extension() == ".jpeg")
  19. {
  20. // 获取图片路径并读取图像
  21. std::string img_path = i.path().string();
  22. cv::Mat img = cv::imread(img_path);
  23. std::vector<DL_RESULT> res;
  24. // 运行推理会话以检测对象
  25. p->RunSession(img, res);
  26. // 对每个检测到的对象进行处理
  27. for (auto& re : res)
  28. {
  29. // 生成随机颜色
  30. cv::RNG rng(cv::getTickCount());
  31. cv::Scalar color(rng.uniform(0, 256), rng.uniform(0, 256), rng.uniform(0, 256));
  32. // 在图像上绘制检测框
  33. cv::rectangle(img, re.box, color, 3);
  34. // 格式化置信度并生成标签
  35. float confidence = floor(100 * re.confidence) / 100;
  36. std::cout << std::fixed << std::setprecision(2);
  37. std::string label = p->classes[re.classId] + " " +
  38. std::to_string(confidence).substr(0, std::to_string(confidence).size() - 4);
  39. // 在图像上绘制标签
  40. cv::rectangle(
  41. img,
  42. cv::Point(re.box.x, re.box.y - 25),
  43. cv::Point(re.box.x + label.length() * 15, re.box.y),
  44. color,
  45. cv::FILLED
  46. );
  47. cv::putText(
  48. img,
  49. label,
  50. cv::Point(re.box.x, re.box.y - 5),
  51. cv::FONT_HERSHEY_SIMPLEX,
  52. 0.75,
  53. cv::Scalar(0, 0, 0),
  54. 2
  55. );
  56. }
  57. // 显示结果并等待用户按下任意键
  58. std::cout << "Press any key to exit" << std::endl;
  59. cv::imshow("Result of Detection", img);
  60. cv::waitKey(0);
  61. cv::destroyAllWindows();
  62. }
  63. }
  64. }
  65. // 对图像进行分类
  66. void Classifier(YOLO_V8*& p)
  67. {
  68. // 获取当前工作目录
  69. std::filesystem::path current_path = std::filesystem::current_path();
  70. // 设置要访问的图片目录路径
  71. std::filesystem::path imgs_path = R"(D:\C++ project\Demo4\Demo4\images\person)";
  72. // 设置类别名称
  73. p->classes = { "person", "normal" };
  74. // 生成随机数引擎
  75. std::random_device rd;
  76. std::mt19937 gen(rd());
  77. std::uniform_int_distribution<int> dis(0, 255);
  78. // 遍历图片目录中的所有文件
  79. for (auto& i : std::filesystem::directory_iterator(imgs_path))
  80. {
  81. // 检查文件是否是图片文件(.jpg, .png)
  82. if (i.path().extension() == ".jpg" || i.path().extension() == ".png")
  83. {
  84. // 获取图片路径并读取图像
  85. std::string img_path = i.path().string();
  86. cv::Mat img = cv::imread(img_path);
  87. std::vector<DL_RESULT> res;
  88. // 运行推理会话以进行图像分类
  89. char* ret = p->RunSession(img, res);
  90. // 绘制分类结果
  91. float positionY = 50;
  92. for (int i = 0; i < res.size(); i++)
  93. {
  94. // 生成随机颜色
  95. int r = dis(gen);
  96. int g = dis(gen);
  97. int b = dis(gen);
  98. // 获取类别名称和置信度
  99. std::string label;
  100. if (res[i].classId >= 0 && res[i].classId < p->classes.size()) {
  101. label = p->classes[res[i].classId] + ": " + std::to_string(res[i].confidence);
  102. }
  103. else {
  104. label = "Unknown";
  105. }
  106. // 在图像上绘制分类标签和置信度
  107. cv::putText(img, label, cv::Point(10, positionY), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(b, g, r), 2);
  108. positionY += 50;
  109. }
  110. // 在窗口中显示分类结果并等待用户按下任意键
  111. cv::imshow("TEST_CLS", img);
  112. cv::waitKey(0);
  113. cv::destroyAllWindows();
  114. // 可选:保存分类结果图像
  115. //cv::imwrite("E:\\output\\" + std::to_string(k) + ".png", img);
  116. }
  117. }
  118. }
  119. // 读取数据集的标签
  120. //int ReadCoCoYaml(YOLO_V8*& p) {
  121. // // 打开YAML文件
  122. // std::ifstream file("D:\\project\\yolov8_main\\ultralytics\\coco.yaml");
  123. // if (!file.is_open())
  124. // {
  125. // // 如果打开文件失败,则输出错误信息
  126. // std::cerr << "Failed to open file" << std::endl;
  127. // return 1;
  128. // }
  129. //
  130. // // 逐行读取文件内容
  131. // std::string line;
  132. // std::vector<std::string> lines;
  133. // while (std::getline(file, line))
  134. // {
  135. // lines.push_back(line);
  136. // }
  137. //
  138. // // 查找类别名称部分的起始和结束位置
  139. // std::size_t start = 0;
  140. // std::size_t end = 0;
  141. // for (std::size_t i = 0; i < lines.size(); i++)
  142. // {
  143. // if (lines[i].find("names:") != std::string::npos)
  144. // {
  145. // start = i + 1;
  146. // }
  147. // else if (start > 0 && lines[i].empty())
  148. // {
  149. // end = i;
  150. // break;
  151. // }
  152. // }
  153. //
  154. // // 提取类别名称
  155. // std::vector<std::string> names;
  156. // for (std::size_t i = start; i < end; i++)
  157. // {
  158. // // 解析类别名称键值对
  159. // std::size_t colon_pos = lines[i].find(':');
  160. // if (colon_pos != std::string::npos)
  161. // {
  162. // std::string name = lines[i].substr(colon_pos + 1);
  163. // // 去除字符串两端的空格
  164. // name = std::regex_replace(name, std::regex("^ +| +$|( ) +"), "$1");
  165. // names.push_back(name);
  166. // }
  167. // }
  168. //
  169. // // 将类别名称赋值给YOLO_V8对象
  170. // p->classes = names;
  171. // return 0;
  172. //}
  173. // 进行检测测试
  174. void DetectTest()
  175. {
  176. #define USE_CUDA
  177. // 创建YOLO_V8对象指针
  178. YOLO_V8* yoloDetector = new YOLO_V8;
  179. // 初始化推理参数
  180. DL_INIT_PARAM params;
  181. params.rectConfidenceThreshold = 0.1;
  182. params.iouThreshold = 0.5;
  183. params.modelPath = "./models/yolov8n.onnx";
  184. params.imgSize = { 640, 640 };
  185. // 设置检测类别为"person"
  186. yoloDetector->classes = { "person" };
  187. #ifdef USE_CUDA
  188. // 如果使用CUDA加速
  189. params.cudaEnable = true;
  190. // 使用GPU FP32推理
  191. params.modelType = YOLO_DETECT_V8;
  192. // 使用GPU FP16推理(注意:需要修改FP16的ONNX模型)
  193. //params.modelType = YOLO_DETECT_V8_HALF;
  194. #else
  195. // 如果不使用CUDA,即使用CPU推理
  196. params.modelType = YOLO_DETECT_V8;
  197. params.cudaEnable = false;
  198. #endif
  199. // 创建推理会话
  200. yoloDetector->CreateSession(params);
  201. // 执行检测函数
  202. Detector(yoloDetector);
  203. }
  204. // 进行分类测试
  205. void ClsTest()
  206. {
  207. // 创建YOLO_V8对象指针
  208. YOLO_V8* yoloDetector = new YOLO_V8;
  209. // 设置分类模型路径
  210. std::string model_path = "./models/yolov8s-cls.onnx";
  211. // 读取COCO数据集标签
  212. /*ReadMuckYaml(yoloDetector);*/
  213. // 初始化推理参数
  214. DL_INIT_PARAM params{ model_path, YOLO_CLS, {224, 224} };
  215. // 创建推理会话
  216. yoloDetector->CreateSession(params);
  217. // 执行分类函数
  218. Classifier(yoloDetector);
  219. }
  220. // 主函数
  221. int main()
  222. {
  223. // 执行检测测试
  224. ClsTest();
  225. // 执行分类测试
  226. //ClsTest();
  227. }

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

inference.h
  1. #pragma once
  2. #define RET_OK nullptr
  3. #ifdef _WIN32
  4. #include <Windows.h>
  5. #include <direct.h>
  6. #include <io.h>
  7. #endif
  8. #include <string>
  9. #include <vector>
  10. #include <cstdio>
  11. #include <opencv2/opencv.hpp>
  12. #include "onnxruntime_cxx_api.h"
  13. #ifdef USE_CUDA
  14. #include <cuda_fp16.h>
  15. #endif
  16. enum MODEL_TYPE
  17. {
  18. //FLOAT32 MODEL
  19. YOLO_DETECT_V8 = 1,
  20. YOLO_POSE = 2,
  21. YOLO_CLS = 3,
  22. //FLOAT16 MODEL
  23. YOLO_DETECT_V8_HALF = 4,
  24. YOLO_POSE_V8_HALF = 5,
  25. };
  26. typedef struct _DL_INIT_PARAM
  27. {
  28. std::string modelPath;
  29. MODEL_TYPE modelType = YOLO_DETECT_V8;
  30. std::vector<int> imgSize = { 640, 640 };
  31. float rectConfidenceThreshold = 0.6;
  32. float iouThreshold = 0.5;
  33. int keyPointsNum = 2;//Note:kpt number for pose
  34. bool cudaEnable = false;
  35. int logSeverityLevel = 3;
  36. int intraOpNumThreads = 1;
  37. } DL_INIT_PARAM;
  38. typedef struct _DL_RESULT
  39. {
  40. int classId;
  41. float confidence;
  42. cv::Rect box;
  43. std::vector<cv::Point2f> keyPoints;
  44. } DL_RESULT;
  45. class YOLO_V8
  46. {
  47. public:
  48. YOLO_V8();
  49. ~YOLO_V8();
  50. public:
  51. char* CreateSession(DL_INIT_PARAM& iParams);
  52. char* RunSession(cv::Mat& iImg, std::vector<DL_RESULT>& oResult);
  53. char* WarmUpSession();
  54. template<typename N>
  55. char* TensorProcess(clock_t& starttime_1, cv::Mat& iImg, N& blob, std::vector<int64_t>& inputNodeDims,
  56. std::vector<DL_RESULT>& oResult);
  57. char* PreProcess(cv::Mat& iImg, std::vector<int> iImgSize, cv::Mat& oImg);
  58. std::vector<std::string> classes{};
  59. private:
  60. Ort::Env env;
  61. Ort::Session* session;
  62. bool cudaEnable;
  63. Ort::RunOptions options;
  64. std::vector<const char*> inputNodeNames;
  65. std::vector<const char*> outputNodeNames;
  66. MODEL_TYPE modelType;
  67. std::vector<int> imgSize;
  68. float rectConfidenceThreshold;
  69. float iouThreshold;
  70. float resizeScales;//letterbox scale
  71. };
inference.cpp
  1. #include "inference.h"
  2. #include <regex>
  3. #define benchmark
  4. #define min(a,b) (((a) < (b)) ? (a) : (b))
  5. YOLO_V8::YOLO_V8() {
  6. }
  7. YOLO_V8::~YOLO_V8() {
  8. delete session;
  9. }
  10. #ifdef USE_CUDA
  11. namespace Ort
  12. {
  13. template<>
  14. struct TypeToTensorType<half> { static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; };
  15. }
  16. #endif
  17. template<typename T>
  18. char* BlobFromImage(cv::Mat& iImg, T& iBlob) {
  19. int channels = iImg.channels();
  20. int imgHeight = iImg.rows;
  21. int imgWidth = iImg.cols;
  22. for (int c = 0; c < channels; c++)
  23. {
  24. for (int h = 0; h < imgHeight; h++)
  25. {
  26. for (int w = 0; w < imgWidth; w++)
  27. {
  28. iBlob[c * imgWidth * imgHeight + h * imgWidth + w] = typename std::remove_pointer<T>::type(
  29. (iImg.at<cv::Vec3b>(h, w)[c]) / 255.0f);
  30. }
  31. }
  32. }
  33. return RET_OK;
  34. }
  35. char* YOLO_V8::PreProcess(cv::Mat& iImg, std::vector<int> iImgSize, cv::Mat& oImg)
  36. {
  37. if (iImg.channels() == 3)
  38. {
  39. oImg = iImg.clone();
  40. cv::cvtColor(oImg, oImg, cv::COLOR_BGR2RGB);
  41. }
  42. else
  43. {
  44. cv::cvtColor(iImg, oImg, cv::COLOR_GRAY2RGB);
  45. }
  46. switch (modelType)
  47. {
  48. case YOLO_DETECT_V8:
  49. case YOLO_POSE:
  50. case YOLO_DETECT_V8_HALF:
  51. case YOLO_POSE_V8_HALF://LetterBox
  52. {
  53. if (iImg.cols >= iImg.rows)
  54. {
  55. resizeScales = iImg.cols / (float)iImgSize.at(0);
  56. cv::resize(oImg, oImg, cv::Size(iImgSize.at(0), int(iImg.rows / resizeScales)));
  57. }
  58. else
  59. {
  60. resizeScales = iImg.rows / (float)iImgSize.at(0);
  61. cv::resize(oImg, oImg, cv::Size(int(iImg.cols / resizeScales), iImgSize.at(1)));
  62. }
  63. cv::Mat tempImg = cv::Mat::zeros(iImgSize.at(0), iImgSize.at(1), CV_8UC3);
  64. oImg.copyTo(tempImg(cv::Rect(0, 0, oImg.cols, oImg.rows)));
  65. oImg = tempImg;
  66. break;
  67. }
  68. case YOLO_CLS://CenterCrop
  69. {
  70. int h = iImg.rows;
  71. int w = iImg.cols;
  72. int m = min(h, w);
  73. int top = (h - m) / 2;
  74. int left = (w - m) / 2;
  75. cv::resize(oImg(cv::Rect(left, top, m, m)), oImg, cv::Size(iImgSize.at(0), iImgSize.at(1)));
  76. break;
  77. }
  78. }
  79. return RET_OK;
  80. }
  81. char* YOLO_V8::CreateSession(DL_INIT_PARAM& iParams) {
  82. char* Ret = RET_OK;
  83. std::regex pattern("[\u4e00-\u9fa5]");
  84. bool result = std::regex_search(iParams.modelPath, pattern);
  85. if (result)
  86. {
  87. Ret = "[YOLO_V8]:Your model path is error.Change your model path without chinese characters.";
  88. std::cout << Ret << std::endl;
  89. return Ret;
  90. }
  91. try
  92. {
  93. rectConfidenceThreshold = iParams.rectConfidenceThreshold;
  94. iouThreshold = iParams.iouThreshold;
  95. imgSize = iParams.imgSize;
  96. modelType = iParams.modelType;
  97. env = Ort::Env(ORT_LOGGING_LEVEL_WARNING, "Yolo");
  98. Ort::SessionOptions sessionOption;
  99. if (iParams.cudaEnable)
  100. {
  101. cudaEnable = iParams.cudaEnable;
  102. OrtCUDAProviderOptions cudaOption;
  103. cudaOption.device_id = 0;
  104. sessionOption.AppendExecutionProvider_CUDA(cudaOption);
  105. }
  106. sessionOption.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
  107. sessionOption.SetIntraOpNumThreads(iParams.intraOpNumThreads);
  108. sessionOption.SetLogSeverityLevel(iParams.logSeverityLevel);
  109. #ifdef _WIN32
  110. int ModelPathSize = MultiByteToWideChar(CP_UTF8, 0, iParams.modelPath.c_str(), static_cast<int>(iParams.modelPath.length()), nullptr, 0);
  111. wchar_t* wide_cstr = new wchar_t[ModelPathSize + 1];
  112. MultiByteToWideChar(CP_UTF8, 0, iParams.modelPath.c_str(), static_cast<int>(iParams.modelPath.length()), wide_cstr, ModelPathSize);
  113. wide_cstr[ModelPathSize] = L'\0';
  114. const wchar_t* modelPath = wide_cstr;
  115. #else
  116. const char* modelPath = iParams.modelPath.c_str();
  117. #endif // _WIN32
  118. session = new Ort::Session(env, modelPath, sessionOption);
  119. Ort::AllocatorWithDefaultOptions allocator;
  120. size_t inputNodesNum = session->GetInputCount();
  121. for (size_t i = 0; i < inputNodesNum; i++)
  122. {
  123. Ort::AllocatedStringPtr input_node_name = session->GetInputNameAllocated(i, allocator);
  124. char* temp_buf = new char[50];
  125. strcpy(temp_buf, input_node_name.get());
  126. inputNodeNames.push_back(temp_buf);
  127. }
  128. size_t OutputNodesNum = session->GetOutputCount();
  129. for (size_t i = 0; i < OutputNodesNum; i++)
  130. {
  131. Ort::AllocatedStringPtr output_node_name = session->GetOutputNameAllocated(i, allocator);
  132. char* temp_buf = new char[10];
  133. strcpy(temp_buf, output_node_name.get());
  134. outputNodeNames.push_back(temp_buf);
  135. }
  136. options = Ort::RunOptions{ nullptr };
  137. WarmUpSession();
  138. return RET_OK;
  139. }
  140. catch (const std::exception& e)
  141. {
  142. const char* str1 = "[YOLO_V8]:";
  143. const char* str2 = e.what();
  144. std::string result = std::string(str1) + std::string(str2);
  145. char* merged = new char[result.length() + 1];
  146. std::strcpy(merged, result.c_str());
  147. std::cout << merged << std::endl;
  148. delete[] merged;
  149. return "[YOLO_V8]:Create session failed.";
  150. }
  151. }
  152. char* YOLO_V8::RunSession(cv::Mat& iImg, std::vector<DL_RESULT>& oResult) {
  153. #ifdef benchmark
  154. clock_t starttime_1 = clock();
  155. #endif // benchmark
  156. char* Ret = RET_OK;
  157. cv::Mat processedImg;
  158. PreProcess(iImg, imgSize, processedImg);
  159. if (modelType < 4)
  160. {
  161. float* blob = new float[processedImg.total() * 3];
  162. BlobFromImage(processedImg, blob);
  163. std::vector<int64_t> inputNodeDims = { 1, 3, imgSize.at(0), imgSize.at(1) };
  164. TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult);
  165. }
  166. else
  167. {
  168. #ifdef USE_CUDA
  169. half* blob = new half[processedImg.total() * 3];
  170. BlobFromImage(processedImg, blob);
  171. std::vector<int64_t> inputNodeDims = { 1,3,imgSize.at(0),imgSize.at(1) };
  172. TensorProcess(starttime_1, iImg, blob, inputNodeDims, oResult);
  173. #endif
  174. }
  175. return Ret;
  176. }
  177. template<typename N>
  178. char* YOLO_V8::TensorProcess(clock_t& starttime_1, cv::Mat& iImg, N& blob, std::vector<int64_t>& inputNodeDims,
  179. std::vector<DL_RESULT>& oResult) {
  180. Ort::Value inputTensor = Ort::Value::CreateTensor<typename std::remove_pointer<N>::type>(
  181. Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1),
  182. inputNodeDims.data(), inputNodeDims.size());
  183. #ifdef benchmark
  184. clock_t starttime_2 = clock();
  185. #endif // benchmark
  186. auto outputTensor = session->Run(options, inputNodeNames.data(), &inputTensor, 1, outputNodeNames.data(),
  187. outputNodeNames.size());
  188. #ifdef benchmark
  189. clock_t starttime_3 = clock();
  190. #endif // benchmark
  191. Ort::TypeInfo typeInfo = outputTensor.front().GetTypeInfo();
  192. auto tensor_info = typeInfo.GetTensorTypeAndShapeInfo();
  193. std::vector<int64_t> outputNodeDims = tensor_info.GetShape();
  194. auto output = outputTensor.front().GetTensorMutableData<typename std::remove_pointer<N>::type>();
  195. delete[] blob;
  196. switch (modelType)
  197. {
  198. case YOLO_DETECT_V8:
  199. case YOLO_DETECT_V8_HALF:
  200. {
  201. int strideNum = outputNodeDims[1];//8400
  202. int signalResultNum = outputNodeDims[2];//84
  203. std::vector<int> class_ids;
  204. std::vector<float> confidences;
  205. std::vector<cv::Rect> boxes;
  206. cv::Mat rawData;
  207. if (modelType == YOLO_DETECT_V8)
  208. {
  209. // FP32
  210. rawData = cv::Mat(strideNum, signalResultNum, CV_32F, output);
  211. }
  212. else
  213. {
  214. // FP16
  215. rawData = cv::Mat(strideNum, signalResultNum, CV_16F, output);
  216. rawData.convertTo(rawData, CV_32F);
  217. }
  218. //Note:
  219. //ultralytics add transpose operator to the output of yolov8 model.which make yolov8/v5/v7 has same shape
  220. //https://github.com/ultralytics/assets/releases/download/v8.1.0/yolov8n.pt
  221. //rowData = rowData.t();
  222. float* data = (float*)rawData.data;
  223. for (int i = 0; i < strideNum; ++i)
  224. {
  225. float* classesScores = data + 4;
  226. cv::Mat scores(1, this->classes.size(), CV_32FC1, classesScores);
  227. cv::Point class_id;
  228. double maxClassScore;
  229. cv::minMaxLoc(scores, 0, &maxClassScore, 0, &class_id);
  230. if (maxClassScore > rectConfidenceThreshold)
  231. {
  232. confidences.push_back(maxClassScore);
  233. class_ids.push_back(class_id.x);
  234. float x = data[0];
  235. float y = data[1];
  236. float w = data[2];
  237. float h = data[3];
  238. int left = int((x - 0.5 * w) * resizeScales);
  239. int top = int((y - 0.5 * h) * resizeScales);
  240. int width = int(w * resizeScales);
  241. int height = int(h * resizeScales);
  242. boxes.push_back(cv::Rect(left, top, width, height));
  243. }
  244. data += signalResultNum;
  245. }
  246. std::vector<int> nmsResult;
  247. cv::dnn::NMSBoxes(boxes, confidences, rectConfidenceThreshold, iouThreshold, nmsResult);
  248. for (int i = 0; i < nmsResult.size(); ++i)
  249. {
  250. int idx = nmsResult[i];
  251. DL_RESULT result;
  252. result.classId = class_ids[idx];
  253. result.confidence = confidences[idx];
  254. result.box = boxes[idx];
  255. oResult.push_back(result);
  256. }
  257. #ifdef benchmark
  258. clock_t starttime_4 = clock();
  259. double pre_process_time = (double)(starttime_2 - starttime_1) / CLOCKS_PER_SEC * 1000;
  260. double process_time = (double)(starttime_3 - starttime_2) / CLOCKS_PER_SEC * 1000;
  261. double post_process_time = (double)(starttime_4 - starttime_3) / CLOCKS_PER_SEC * 1000;
  262. if (cudaEnable)
  263. {
  264. std::cout << "[YOLO_V8(CUDA)]: " << pre_process_time << "ms pre-process, " << process_time << "ms inference, " << post_process_time << "ms post-process." << std::endl;
  265. }
  266. else
  267. {
  268. std::cout << "[YOLO_V8(CPU)]: " << pre_process_time << "ms pre-process, " << process_time << "ms inference, " << post_process_time << "ms post-process." << std::endl;
  269. }
  270. #endif // benchmark
  271. break;
  272. }
  273. case YOLO_CLS:
  274. {
  275. DL_RESULT result;
  276. for (int i = 0; i < this->classes.size(); i++)
  277. {
  278. result.classId = i;
  279. result.confidence = output[i];
  280. oResult.push_back(result);
  281. }
  282. break;
  283. }
  284. default:
  285. std::cout << "[YOLO_V8]: " << "Not support model type." << std::endl;
  286. }
  287. return RET_OK;
  288. }
  289. char* YOLO_V8::WarmUpSession() {
  290. clock_t starttime_1 = clock();
  291. cv::Mat iImg = cv::Mat(cv::Size(imgSize.at(0), imgSize.at(1)), CV_8UC3);
  292. cv::Mat processedImg;
  293. PreProcess(iImg, imgSize, processedImg);
  294. if (modelType < 4)
  295. {
  296. float* blob = new float[iImg.total() * 3];
  297. BlobFromImage(processedImg, blob);
  298. std::vector<int64_t> YOLO_input_node_dims = { 1, 3, imgSize.at(0), imgSize.at(1) };
  299. Ort::Value input_tensor = Ort::Value::CreateTensor<float>(
  300. Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU), blob, 3 * imgSize.at(0) * imgSize.at(1),
  301. YOLO_input_node_dims.data(), YOLO_input_node_dims.size());
  302. auto output_tensors = session->Run(options, inputNodeNames.data(), &input_tensor, 1, outputNodeNames.data(),
  303. outputNodeNames.size());
  304. delete[] blob;
  305. clock_t starttime_4 = clock();
  306. double post_process_time = (double)(starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000;
  307. if (cudaEnable)
  308. {
  309. std::cout << "[YOLO_V8(CUDA)]: " << "Cuda warm-up cost " << post_process_time << " ms. " << std::endl;
  310. }
  311. }
  312. else
  313. {
  314. #ifdef USE_CUDA
  315. half* blob = new half[iImg.total() * 3];
  316. BlobFromImage(processedImg, blob);
  317. std::vector<int64_t> YOLO_input_node_dims = { 1,3,imgSize.at(0),imgSize.at(1) };
  318. 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());
  319. auto output_tensors = session->Run(options, inputNodeNames.data(), &input_tensor, 1, outputNodeNames.data(), outputNodeNames.size());
  320. delete[] blob;
  321. clock_t starttime_4 = clock();
  322. double post_process_time = (double)(starttime_4 - starttime_1) / CLOCKS_PER_SEC * 1000;
  323. if (cudaEnable)
  324. {
  325. std::cout << "[YOLO_V8(CUDA)]: " << "Cuda warm-up cost " << post_process_time << " ms. " << std::endl;
  326. }
  327. #endif
  328. }
  329. return RET_OK;
  330. }

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

闽ICP备14008679号