C#简单使用Yolov5的Onnx格式模型进行目标检测

背景

最近要离职了,同事需要了解一下C#如何使用yolov5系列onnx格式模型进行目标检测,由于其对C#不熟练,可能会影响公司后续的开发进度,所以趁着还在,赶紧把手尾搞好。

方案

1、创建一个C# DotNet 8 控制台项目**可千万注意不要选了DotNetFramework框架哦**,命名为TestNugetCpuOnnx,并生成解决方案,产生bin目录

2、 在Nuget中安装我的包BingLing.Yolov5Onnx.Cpu

由于这个是可以跨平台调用的,我并没有把运行时一起打包过去,我当前示例的系统是windows,因此我还需要安装EmguCv.runtime.windows

3、准备好我们的onnx文件和一个json格式的配置文件 ,如果你没有的话,可以到我的码云里下载

BingLing.Yolov5Onnx.Cpu: C#使用cpu使用 yolov5 模型的onnx格式文件进行推理,简化你的编码 (gitee.com)

下载完毕后将其中的yolov5s.onnx,以及yolov5_onnx.json这两个文件一起放到bin/Debug/net8.0这个目录下。值得一提的是,你还需要准备一张图片,修改名字为down.jpeg也放到这个目录下,如果找不到,直接从我的博客下也行。

down.jpeg【网络获取,觉侵联删】

4、 修改Program.cs代码内容为如下

cs 复制代码
using BingLing.Yolov5Onnx.Cpu;
using Emgu.CV.Structure;
using Emgu.CV;
using System.Collections.Concurrent;

namespace TestNugetCpuOnnx
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Yolov5Onnx yolov5Onnx = new("yolov5_onnx.json");
            Mat mat = new("down.jpeg");
            MCvScalar color = new(255, 0, 0);
            ConcurrentDictionary<int, List<Prediction>> dictionary = yolov5Onnx.DetectAllOut(mat);

            foreach (List<Prediction> predictions in dictionary.Values)
            {
                foreach (var prediction in predictions)
                {
                    int x = (int)((prediction.X - prediction.Width / 2));
                    int y = (int)((prediction.Y - prediction.Height / 2));
                    int width = (int)(prediction.Width);
                    int height = (int)(prediction.Height);
                    CvInvoke.Rectangle(mat, new System.Drawing.Rectangle(x, y, width, height), color);
                    CvInvoke.PutText(mat, $"k:{prediction.Kind}", new System.Drawing.Point(x, y + 20), Emgu.CV.CvEnum.FontFace.HersheyDuplex, 1, color);
                    CvInvoke.PutText(mat, $"c:{prediction.Confidence:0.00}", new System.Drawing.Point(x, y + 50), Emgu.CV.CvEnum.FontFace.HersheyDuplex, 1, color);
                }
            }
            CvInvoke.Imshow("mat", mat);
            CvInvoke.WaitKey(0);
            CvInvoke.DestroyAllWindows();
        }
    }
}

5、运行程序,查看结果,其中k为kind,c为confidence

6、安装EmguCv.runtime.ubuntu在linux系统下运行结果

注意发布成linux可执行程序,发布方法前面博客已经论述过,这里不再重复

相关推荐
Wireless_wifi66 分钟前
Why Choose IPQ9574 for Your WiFi 7 Solution
linux·人工智能·5g
Ar-Sr-Na8 分钟前
工作路演PPT处理,交给Workbuddy
人工智能·powerpoint·workbuddy开发者分享季
阿洛学长8 分钟前
Cursor下载安装使用教程(最新详细图文)
人工智能·gpt·深度学习·ai·ai编程
2603_955279709 分钟前
城市与雨水的隐秘对话
人工智能
renhongxia113 分钟前
原生多模态对应用架构的重塑
人工智能·深度学习·机器学习·自然语言处理·架构·机器人
俊哥V14 分钟前
每日 AI 研究简报 · 2026-07-03
人工智能·ai
Nomarsgo20 分钟前
工控机蓝屏怎么办?
人工智能·科技·计算机视觉·视觉检测·电脑
金融小师妹21 分钟前
人工智能推演框架:非农降温信号如何重构黄金定价模型
数据结构·人工智能·机器学习·transformer
HavenlonLabs25 分钟前
Havenlon 思考录(十一):系统的冷,不是对人,而是对风险
人工智能·安全威胁分析·安全架构·havenlon
林澈在路上26 分钟前
最新版权清晰 AI音乐写歌工具软件App推荐 商用全场景实测指南
数据库·人工智能·ai·aigc·音频