c# 部署onnx分类模型

目录

1.环境

 2.代码

3.效果


1.环境

gpu3060+cuda11.1+vs2019

+Microsoft.ML.OnnxRuntime

+SixLabors.ImageSharp

 2.代码

using System;
using System.Collections.Generic;
using System.Linq;

using Microsoft.ML.OnnxRuntime.Tensors;  // DenseTensor

using SixLabors.ImageSharp;  // Image, Size
using SixLabors.ImageSharp.PixelFormats;  // Rgb24
using SixLabors.ImageSharp.Processing;  // image.Mutate

namespace Microsoft.ML.OnnxRuntime.ResNet50v2Sample
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Read paths
            string modelFilePath = @"E:\code\Csharp\onnxruntime-master\csharp\sample\Microsoft.ML.OnnxRuntime.ResNet50v2Sample\resnet50-v2-7.onnx";
            string imageFilePath = @"E:\code\Csharp\onnxruntime-master\csharp\sample\Microsoft.ML.OnnxRuntime.ResNet50v2Sample\dog.jpeg";

            // Read image
            // Rgb24:Pixel type containing three 8-bit unsigned normalized values ranging from 0 to
            //        255. The color components are stored in red, green, blue order
            // SixLabors.ImageSharp.Image
            using Image<Rgb24> image = Image.Load<Rgb24>(imageFilePath);  // 以rgb形式读取图片

            // Resize image
            image.Mutate(x =>
            {
                x.Resize(new ResizeOptions
                {
                    Size = new Size(224, 224),
                    Mode = ResizeMode.Crop
                });
            });

            //image.Mutate(x =>
            //        x.Resize(224, 224)
            //);


            // Preprocess image
            Tensor<float> input = new DenseTensor<float>(new[] { 1, 3, 224, 224 });  // 声明4维变量:(b, c, h, w)
            var mean = new[] { 0.485f, 0.456f, 0.406f };
            var stddev = new[] { 0.229f, 0.224f, 0.225f };
            for (int y = 0; y < image.Height; y++)
            {
                Span<Rgb24> pixelSpan = image.GetPixelRowSpan(y);
                for (int x = 0; x < image.Width; x++)  // 先行后列
                {
                    input[0, 0, y, x] = ((pixelSpan[x].R / 255f) - mean[0]) / stddev[0];
                    input[0, 1, y, x] = ((pixelSpan[x].G / 255f) - mean[1]) / stddev[1];
                    input[0, 2, y, x] = ((pixelSpan[x].B / 255f) - mean[2]) / stddev[2];
                }
            }

            // Setup inputs
            var inputs = new List<NamedOnnxValue>
            {
                NamedOnnxValue.CreateFromTensor("data", input)
            };

            // Run inference
            using var session = new InferenceSession(modelFilePath);
            using IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results = session.Run(inputs);

            // Postprocess to get softmax vector
            IEnumerable<float> output = results.First().AsEnumerable<float>();  // First(): The first element in the specified sequence. AsEnumerable:
            float sum = output.Sum(x => (float)Math.Exp(x));   // sum(e^x)
            IEnumerable<float> softmax = output.Select(x => (float)Math.Exp(x) / sum);  // e^x / sum

            // Extract top 10 predicted classes
            IEnumerable<Prediction> top10 = softmax.Select((x, i) => new Prediction { Label = LabelMap.Labels[i], Confidence = x })
                               .OrderByDescending(x => x.Confidence)
                               .Take(10);

            // Print results to console
            Console.WriteLine("Top 10 predictions for ResNet50 v2...");
            Console.WriteLine("--------------------------------------------------------------");
            foreach (var t in top10)
            {
                Console.WriteLine($"Label: {t.Label}, Confidence: {t.Confidence}");
            }
        }
    }
}

3.效果

输入图片:

网络输出:

 

 第一个是金毛猎犬。

  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 19
    评论
Yolov5 是一个基于 Pytorch 的目标检测模型,将其转换为 ONNX 格式可以方便地在各种平台上部署。如果你想在 C# 中使用 ONNX 格式的 Yolov5 分类模型,可以按照以下步骤进行: 1. 使用 Pytorch 将 Yolov5 模型转换为 ONNX 格式。可以使用以下命令: ``` python models/export.py --weights yolov5s.pt --img-size 640 --batch-size 1 ``` 其中,`yolov5s.pt` 是 Yolov5 模型的权重文件,`--img-size` 是输入图片的尺寸,`--batch-size` 是批量处理的图片数量。执行该命令后,会在 `models` 文件夹下生成一个 `yolov5s.onnx` 文件,即转换后的模型。 2. 在 C# 中使用 ONNXRuntime 运行 Yolov5 模型。可以使用以下代码: ```csharp using Microsoft.ML.OnnxRuntime; using Microsoft.ML.OnnxRuntime.Tensors; // 创建 ONNXRuntime 执行器 var options = new SessionOptions(); var session = new InferenceSession("models/yolov5s.onnx", options); // 预处理输入图片 var image = Image.Load<Rgb24>("test.jpg"); var resized = image.Resize(new ResizeOptions { Size = new Size(640, 640), Mode = ResizeMode.Max }); var buffer = resized.SavePixelData(); // 将输入图片转换为 Tensor var tensor = new DenseTensor<float>(new[] { 1, 3, 640, 640 }); for (int i = 0; i < buffer.Length; i += 3) { tensor[0, 0, i / 3 % 640, i / 3 / 640] = buffer[i]; tensor[0, 1, i / 3 % 640, i / 3 / 640] = buffer[i + 1]; tensor[0, 2, i / 3 % 640, i / 3 / 640] = buffer[i + 2]; } // 执行模型推理 var inputs = new List<NamedOnnxValue> { NamedOnnxValue.CreateFromTensor("input", tensor) }; var outputs = session.Run(inputs); var result = outputs.FirstOrDefault()?.AsTensor<float>().ToArray(); // 处理模型输出 // TODO ``` 在上述代码中,`test.jpg` 是输入图片的路径,`options` 是 ONNXRuntime 的配置选项,`session` 是 ONNXRuntime 的执行器,`tensor` 是将输入图片转换为的 Tensor,`inputs` 是执行模型推理时的输入参数,`outputs` 是执行模型推理后的输出结果。你需要根据具体的 Yolov5 模型结构和输出结果进行相应的处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr.Q

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值