方案

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也放到这个目录下,如果找不到,直接从我的博客下也行。

4、 修改Program.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可执行程序,发布方法前面博客已经论述过,这里不再重复 

原文链接

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

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐