c# 部署onnx定位模型

目录

1.环境

2.代码

3.效果


1.环境

gpu3060+cuda11.1+vs2019

+Microsoft.ML.OnnxRuntime

+SixLabors.ImageSharp

2.代码

权重https://github.com/onnx/models/blob/master/vision/object_detection_segmentation/faster-rcnn/model/FasterRCNN-10.onnxicon-default.png?t=L9C2https://github.com/onnx/models/blob/master/vision/object_detection_segmentation/faster-rcnn/model/FasterRCNN-10.onnx

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.ML.OnnxRuntime.Tensors;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.Fonts;

namespace Microsoft.ML.OnnxRuntime.FasterRcnnSample
{
    class Program
    {
        public static void Main(string[] args)
        {
            // Read paths
            string modelFilePath = @"E:\code\Csharp\onnxruntime-master\csharp\sample\Microsoft.ML.OnnxRuntime.FasterRcnnSample\FasterRCNN-10.onnx";
            string imageFilePath = @"E:\code\Csharp\onnxruntime-master\csharp\sample\Microsoft.ML.OnnxRuntime.FasterRcnnSample\demo.jpg";
            string outImageFilePath = "outputs.jpg";
            //System.IO.Directory.CreateDirectory(outImageFilePath);


            // Read image
            using Image<Rgb24> image = Image.Load<Rgb24>(imageFilePath);

            // Resize image
            float ratio = 800f / Math.Min(image.Width, image.Height);
            image.Mutate(x => x.Resize((int)(ratio * image.Width), (int)(ratio * image.Height)));

            // Preprocess image
            var paddedHeight = (int)(Math.Ceiling(image.Height / 32f) * 32f);
            var paddedWidth = (int)(Math.Ceiling(image.Width / 32f) * 32f);
            Tensor<float> input = new DenseTensor<float>(new[] { 3, paddedHeight, paddedWidth });
            var mean = new[] { 102.9801f, 115.9465f, 122.7717f };
            for (int y = paddedHeight - image.Height; y < image.Height; y++)
            {
                Span<Rgb24> pixelSpan = image.GetPixelRowSpan(y);
                for (int x = paddedWidth - image.Width; x < image.Width; x++)
                {
                    input[0, y, x] = pixelSpan[x].B - mean[0];
                    input[1, y, x] = pixelSpan[x].G - mean[1];
                    input[2, y, x] = pixelSpan[x].R - mean[2];
                }
            }

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

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

            // Postprocess to get predictions
            var resultsArray = results.ToArray();
            float[] boxes = resultsArray[0].AsEnumerable<float>().ToArray();
            long[] labels = resultsArray[1].AsEnumerable<long>().ToArray();
            float[] confidences = resultsArray[2].AsEnumerable<float>().ToArray();
            var predictions = new List<Prediction>();
            var minConfidence = 0.7f;
            for (int i = 0; i < boxes.Length - 4; i += 4)
            {
                var index = i / 4;
                if (confidences[index] >= minConfidence)
                {
                    predictions.Add(new Prediction
                    {
                        Box = new Box(boxes[i], boxes[i + 1], boxes[i + 2], boxes[i + 3]),
                        Label = LabelMap.Labels[labels[index]],
                        Confidence = confidences[index]
                    });
                }
            }

            // Put boxes, labels and confidence on image and save for viewing
            using var outputImage = File.OpenWrite(outImageFilePath);
            Font font = SystemFonts.CreateFont("Arial", 16);
            foreach (var p in predictions)
            {
                image.Mutate(x =>
                {
                    x.DrawLines(Color.Red, 2f, new PointF[] {

                        new PointF(p.Box.Xmin, p.Box.Ymin),
                        new PointF(p.Box.Xmax, p.Box.Ymin),

                        new PointF(p.Box.Xmax, p.Box.Ymin),
                        new PointF(p.Box.Xmax, p.Box.Ymax),

                        new PointF(p.Box.Xmax, p.Box.Ymax),
                        new PointF(p.Box.Xmin, p.Box.Ymax),

                        new PointF(p.Box.Xmin, p.Box.Ymax),
                        new PointF(p.Box.Xmin, p.Box.Ymin)
                    });
                    x.DrawText($"{p.Label}, {p.Confidence:0.00}", font, Color.White, new PointF(p.Box.Xmin, p.Box.Ymin));
                });
            }
            image.SaveAsJpeg(outputImage);
        }
    }
}

3.效果

  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
要在C#部署yolov7onnx模型,您可以按照以下步骤进行: 1. 安装ONNX Runtime:您需要下载并安装ONNX Runtime,可以从官方网站 https://github.com/microsoft/onnxruntime/releases 下载最新版本的ONNX Runtime。 2. 加载模型:您需要在C#代码中加载yolov7onnx模型。可以使用ONNX Runtime提供的C# API来加载模型。 3. 准备输入数据:在使用模型之前,您需要准备输入数据。对于yolov7onnx模型,输入数据通常是图像。 4. 运行模型:使用ONNX Runtime提供的Run方法来运行模型,并传递输入数据。模型将返回输出数据,通常是包含检测结果的框和概率的张量。 5. 处理输出数据:处理输出数据以获取检测结果,并将其显示在图像上。 下面是一个简单示例,演示如何在C#中加载yolov7onnx模型并对图像进行目标检测: ``` using System; using System.Drawing; using System.Linq; using Microsoft.ML.OnnxRuntime; using Microsoft.ML.OnnxRuntime.Tensors; public class YOLOv7OnnxDetector { private readonly InferenceSession _session; public YOLOv7OnnxDetector(string modelPath) { _session = new InferenceSession(modelPath); } public BoundingBox[] Detect(Image image) { // Prepare input data var inputMeta = _session.InputMetadata.FirstOrDefault(); if (inputMeta == null || inputMeta.Key != "input") { throw new Exception("Invalid input metadata"); } var tensor = new DenseTensor<float>(new[] { 1, 3, inputMeta.Value.Dimensions[1], inputMeta.Value.Dimensions[2] }); // TODO: Fill tensor with image data // Run model var inputs = new[] { new NamedOnnxValue("input", tensor) }; var outputs = _session.Run(inputs); var outputMeta = _session.OutputMetadata.FirstOrDefault(); if (outputMeta == null || outputMeta.Key != "output") { throw new Exception("Invalid output metadata"); } var output = outputs.First().AsTensor<float>(); // Process output data var boxes = new List<BoundingBox>(); // TODO: Process output tensor to get bounding boxes return boxes.ToArray(); } } public class BoundingBox { public float Left { get; set; } public float Top { get; set; } public float Width { get; set; } public float Height { get; set; } public float Confidence { get; set; } public string Label { get; set; } } ``` 请注意,上面的示例仅提供了一个框架,并且需要根据您的具体情况进行修改。在实际使用中,您需要填充输入数据,并根据模型的输出来处理检测结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mr.Q

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

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

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

打赏作者

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

抵扣说明:

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

余额充值