news 2026/5/1 8:48:40

在C#上运行YOLOv11模型---CPU版

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
在C#上运行YOLOv11模型---CPU版

一. 模型导出

二. 环境搭建

三. 代码程序

参考链接:https://blog.csdn.net/qq_41375318/article/details/142747415


1. 模型导出

参考链接:https://docs.ultralytics.com/zh/modes/export/#cli

将训练完成的YOLO模型导出成ONNX格式,代码如下:

from ultralytics import YOLO # Load a model model = YOLO("yolo11n.pt") # load an official model model = YOLO("path/to/best.pt") # load a custom-trained model # Export the model model.export(format="onnx")

成功导出的onnx模型储存在yolo模型的同级目录下


2. 环境搭建

主要包括C#中的Nuget包下载,其中需要的DLL包括4个:

  • Microsoft.ML.OnnxRuntime
  • Microsoft.ML.OnnxRuntime.Managed
  • OpenCvSharp4
  • OpenCvSharp4.runtime.win

3. 代码程序

3.1 检测结果类

public class DetectionResult { public DetectionResult(int ClassId, string Class, Rect Rect, float Confidence) { this.ClassId = ClassId; this.Confidence = Confidence; this.Rect = Rect; this.Class = Class; } public string Class { get; set; } public int ClassId { get; set; } public float Confidence { get; set; } public Rect Rect { get; set; } }

3.2 变量和Tanspose函数

string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png"; string image_path = ""; string model_path; string classer_path; public string[] class_names; public int class_num; DateTime dt1 = DateTime.Now; DateTime dt2 = DateTime.Now; int input_height; int input_width; float ratio_height; float ratio_width; InferenceSession onnx_session; int box_num; float conf_threshold; float nms_threshold; public unsafe float[] Transpose(float[] tensorData, int rows, int cols) { float[] transposedTensorData = new float[tensorData.Length]; fixed (float* pTensorData = tensorData) { fixed (float* pTransposedData = transposedTensorData) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { int index = i * cols + j; int transposedIndex = j * rows + i; pTransposedData[transposedIndex] = pTensorData[index]; } } } } return transposedTensorData; }

3.2 加载模型与label.txt

private void Form1_Load(object sender, EventArgs e) { model_path =@"...\...\model\yolo11n.onnx"; //创建输出会话,用于输出模型读取信息 SessionOptions options = new SessionOptions(); options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_INFO; options.AppendExecutionProvider_CPU(0);// 设置为CPU上运行 // 创建推理模型类,读取模型文件 onnx_session = new InferenceSession(model_path, options);//model_path 为onnx模型文件的路径 input_height = 640; input_width = 640; box_num = 8400; conf_threshold = 0.25f; nms_threshold = 0.5f; classer_path = @"...\...\model\label.txt"; class_names = File.ReadAllLines(classer_path, Encoding.UTF8); class_num = class_names.Length; // 图片路径 image_path = @"...\...\image1.jpg"; pictureBox1.Image = new Bitmap(image_path); }

3.3 开始检测推理

private void button2_Click(object sender, EventArgs e) { if (image_path == "") { return; } button2.Enabled = false; pictureBox2.Image = null; textBox1.Text = ""; Application.DoEvents(); Mat image = new Mat(image_path); //图片缩放 int height = image.Rows; int width = image.Cols; Mat temp_image = image.Clone(); if (height > input_height || width > input_width) { float scale = Math.Min((float)input_height / height, (float)input_width / width); OpenCvSharp.Size new_size = new OpenCvSharp.Size((int)(width * scale), (int)(height * scale)); Cv2.Resize(image, temp_image, new_size); } ratio_height = (float)height / temp_image.Rows; ratio_width = (float)width / temp_image.Cols; Mat input_img = new Mat(); Cv2.CopyMakeBorder(temp_image, input_img, 0, input_height - temp_image.Rows, 0, input_width - temp_image.Cols, BorderTypes.Constant, 0); //Cv2.ImShow("input_img", input_img); //输入Tensor Tensor<float> input_tensor = new DenseTensor<float>(new[] { 1, 3, 640, 640 }); for (int y = 0; y < input_img.Height; y++) { for (int x = 0; x < input_img.Width; x++) { input_tensor[0, 0, y, x] = input_img.At<Vec3b>(y, x)[0] / 255f; input_tensor[0, 1, y, x] = input_img.At<Vec3b>(y, x)[1] / 255f; input_tensor[0, 2, y, x] = input_img.At<Vec3b>(y, x)[2] / 255f; } } List<NamedOnnxValue> input_container = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor("images", input_tensor) }; //推理 dt1 = DateTime.Now; var ort_outputs = onnx_session.Run(input_container).ToArray(); dt2 = DateTime.Now; float[] data = Transpose(ort_outputs[0].AsTensor<float>().ToArray(), 4 + class_num, box_num); float[] confidenceInfo = new float[class_num]; float[] rectData = new float[4]; List<DetectionResult> detResults = new List<DetectionResult>(); for (int i = 0; i < box_num; i++) { Array.Copy(data, i * (class_num + 4), rectData, 0, 4); Array.Copy(data, i * (class_num + 4) + 4, confidenceInfo, 0, class_num); float score = confidenceInfo.Max(); // 获取最大值 int maxIndex = Array.IndexOf(confidenceInfo, score); // 获取最大值的位置 int _centerX = (int)(rectData[0] * ratio_width); int _centerY = (int)(rectData[1] * ratio_height); int _width = (int)(rectData[2] * ratio_width); int _height = (int)(rectData[3] * ratio_height); detResults.Add(new DetectionResult( maxIndex, class_names[maxIndex], new Rect(_centerX - _width / 2, _centerY - _height / 2, _width, _height), score)); } //NMS CvDnn.NMSBoxes(detResults.Select(x => x.Rect), detResults.Select(x => x.Confidence), conf_threshold, nms_threshold, out int[] indices); detResults = detResults.Where((x, index) => indices.Contains(index)).ToList(); //绘制结果 Mat result_image = image.Clone(); foreach (DetectionResult r in detResults) { Cv2.PutText(result_image, $"{r.Class}:{r.Confidence:P0}", new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2); Cv2.Rectangle(result_image, r.Rect, Scalar.Red, thickness: 2); } pictureBox2.Image = new Bitmap(result_image.ToMemoryStream()); textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms"; button2.Enabled = true; }

注意:设置picture1picture2SizeMode属性为Zoom

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/1 4:43:28

计算机Java毕设实战-基于javaEE的二手手机交易交换出售平台的设计与实现基于javaEE的二手手机交易平台的设计与实现【完整源码+LW+部署说明+演示视频,全bao一条龙等】

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华
网站建设 2026/5/1 4:42:08

Altium Designer 初次实战:STM8S103F3 最小系统板设计全流程心得

前言作为电子信息工程专业的大二学生&#xff0c;这是我第一次接触 Altium Designer&#xff08;AD21&#xff09;这款专业 PCB 设计软件。从最初连 “库文件” 是什么都不知道&#xff0c;到跟着老师的节奏一步步进阶 —— 先练单管放大电路、再攻 51 单片机相关设计&#xff…

作者头像 李华
网站建设 2026/5/1 4:43:15

Dify解析加密PDF卡顿崩溃?5大内存泄漏点全解析,速查避坑

第一章&#xff1a;加密 PDF 解析的 Dify 内存占用在处理加密 PDF 文件时&#xff0c;Dify 平台面临显著的内存消耗问题。这类文件通常需要先解密再解析内容&#xff0c;而解密过程涉及完整的文档加载与密钥验证&#xff0c;导致大量临时对象驻留在内存中。尤其当并发请求增多或…

作者头像 李华
网站建设 2026/5/1 7:52:11

云原生Agent Docker网络配置完全手册(从入门到高可用架构)

第一章&#xff1a;云原生Agent与Docker网络概述在现代云原生架构中&#xff0c;Agent 通常指部署在节点上的轻量级服务进程&#xff0c;用于采集监控数据、执行调度指令或管理容器生命周期。这类 Agent 需要与 Docker 守护进程深度集成&#xff0c;并通过高效的网络机制与其他…

作者头像 李华
网站建设 2026/5/1 6:48:05

T30 天正结构 V1.0:建筑结构设计高效之选下载安装教程

前言 天正出品建筑结构设计利器 ——T30 天正结构 V1.0&#xff0c;深度适配 AutoCAD 平台&#xff0c;主打构件设计到施工图交付全流程赋能&#xff0c;支持多专业协同&#xff0c;让结构工程师高效出规范图纸。 版本亮点 全品类构件精细化设计覆盖柱、梁、剪力墙、楼板、楼…

作者头像 李华