在 C# 中调用 YOLOv8 模型进行目标检测,通常的做法是使用 YOLOv8 的 Python API 或 ONNX 模型,然后通过 C# 与 Python 或 ONNX 进行交互。

在 C# 中调用 YOLOv8 模型进行目标检测,通常的做法是使用 YOLOv8 的 Python API 或 ONNX 模型,然后通过 C# 与 Python 或 ONNX 进行交互。以下是两种常见的方法来在 C# 中实现这个目标:
方法 1:使用 Python 与 C# 交互
这是一种常见的做法,在 C# 中通过调用 Python 脚本来运行 YOLOv8 模型。
步骤:

1.准备 Python 环境
首先,确保你已经安装了 Python 和 YOLOv8 所需的库(如 ultralytics)。你可以在命令行中使用以下命令安装:

 pip install yolov8

2.创建 Python 脚本
写一个 Python 脚本 yolov8_inference.py,用来加载 YOLOv8 模型并进行推理。例如:

   from yolov8 import YOLO
   import sys
   import json

   def run_inference(image_path):
       # 加载模型
       model = YOLO('yolov8.pt')
       # 运行推理
       results = model(image_path)
       # 获取检测结果
       detections = results.pandas().xywh[0].to_dict(orient='records')
       return detections

   if __name__ == "__main__":
       image_path = sys.argv[1]
       detections = run_inference(image_path)
       # 将检测结果输出为 JSON 格式
       print(json.dumps(detections))

3.C# 调用 Python 脚本
使用 C# 的 Process 类来调用 Python 脚本。以下是一个示例代码:

using System;
   using System.Diagnostics;
   using System.IO;

   class Program
   {
       static void Main(string[] args)
       {
           string imagePath = @"path_to_your_image.jpg";
           string pythonScript = @"path_to_your_python_script\yolov8_inference.py";
           string pythonInterpreter = @"C:\path\to\python.exe";  // 你的 Python 安装路径

           // 创建进程启动信息
           ProcessStartInfo startInfo = new ProcessStartInfo
           {
               FileName = pythonInterpreter,
               Arguments = $"{pythonScript} {imagePath}",
               RedirectStandardOutput = true,  // 重定向标准输出
               UseShellExecute = false,        // 不使用操作系统外壳
               CreateNoWindow = true           // 不显示命令行窗口
           };

           // 启动进程并读取输出
           using (Process process = Process.Start(startInfo))
           using (StreamReader reader = process.StandardOutput)
           {
               string result = reader.ReadToEnd();
               Console.WriteLine("Detection Results: ");
               Console.WriteLine(result);
           }
       }
   }

在这个示例中,C# 程序通过 Process.Start 调用 Python 脚本,传递图像路径作为参数,并捕获 Python 脚本的输出结果。Python 脚本输出检测结果为 JSON 格式,C# 程序解析并显示结果。

方法 2:使用 ONNX 模型与 C# 调用
如果你不想通过 Python 交互,可以将 YOLOv8 模型导出为 ONNX (Open Neural Network Exchange) 格式,然后在 C# 中使用 ONNX Runtime 来进行推理。
步骤:

1.导出 YOLOv8 模型为 ONNX 格式
使用 Python 导出 YOLOv8 模型为 ONNX 格式。假设你已经安装了 YOLOv8 和 ONNX 导出工具,以下是导出代码:

   from yolov8 import YOLO

   model = YOLO('yolov8.pt')  # 加载 YOLOv8 模型
   model.export(format='onnx')  # 导出为 ONNX 格式

这会将 yolov8.pt 模型转换为 yolov8.onnx,保存在当前目录中。

2.在 C# 中使用 ONNX Runtime
使用 ONNX Runtime 在 C# 中加载并推理模型。你需要安装 ONNX Runtime 的 NuGet 包:

   dotnet add package Microsoft.ML.OnnxRuntime

然后在 C# 中加载并运行推理:

  using System;
   using System.Linq;
   using Microsoft.ML.OnnxRuntime;
   using Microsoft.ML.OnnxRuntime.Tensors;

   class Program
   {
       static void Main(string[] args)
       {
           string modelPath = @"path_to_yolov8.onnx";  // YOLOv8 ONNX 模型文件路径
           string imagePath = @"path_to_your_image.jpg";  // 输入图像路径

           // 加载 ONNX 模型
           var session = new InferenceSession(modelPath);

           // 载入图像并进行处理(如图像预处理:归一化、调整大小等)
           var imageTensor = PreprocessImage(imagePath);

           // 创建输入的命名张量
           var inputs = new NamedOnnxValue[]
           {
               NamedOnnxValue.CreateFromTensor("input", imageTensor)
           };

           // 执行推理
           var results = session.Run(inputs);

           // 获取输出结果并处理(如提取检测框等)
           var outputTensor = results.First().AsTensor<float>();
           var detectionResults = ProcessDetectionOutput(outputTensor);

           // 显示检测结果
           foreach (var detection in detectionResults)
           {
               Console.WriteLine($"Class: {detection.Class}, Confidence: {detection.Confidence}, Box: {string.Join(",", detection.Box)}");
           }
       }

       static Tensor<float> PreprocessImage(string imagePath)
       {
           // 在此处进行图像预处理,例如调整大小、归一化等,返回张量
           // 这是一个简化示例,具体处理会根据模型输入要求来调整
           return new DenseTensor<float>(new float[] { /* 预处理后的数据 */ }, new int[] { 1, 3, 640, 640 });
       }

       static Detection[] ProcessDetectionOutput(Tensor<float> output)
       {
           // 解析输出数据,提取检测框、类别和置信度等
           // 这取决于 YOLOv8 输出的具体格式
           return new Detection[]
           {
               new Detection { Class = 0, Confidence = 0.95f, Box = new float[] { 100, 100, 200, 200 } }
           };
       }
   }

   public class Detection
   {
       public int Class { get; set; }
       public float Confidence { get; set; }
       public float[] Box { get; set; }
   }

在这个示例中,C# 使用 ONNX Runtime 加载 YOLOv8 的 ONNX 模型,并对输入图像进行推理。你需要根据实际模型的输入输出格式进行适当的图像预处理和结果解析。
总结

方法 1:使用 Python 与 C# 交互:通过在 C# 中调用 Python 脚本,能够直接利用 YOLOv8 的 Python API 进行推理。这种方法简单直接,但需要在 C# 中配置和调用 Python 环境。
方法 2:使用 ONNX 模型与 C# 调用:将 YOLOv8 模型导出为 ONNX 格式,在 C# 中使用 ONNX Runtime 进行推理。这种方法无需依赖 Python,适合纯 C# 环境,适用于部署到生产环境时。

两种方法各有优缺点,选择哪种取决于你的项目需求和环境配置。

作者:踹断瘸子那条好腿.

物联沃分享整理
物联沃-IOTWORD物联网 » 在 C# 中调用 YOLOv8 模型进行目标检测,通常的做法是使用 YOLOv8 的 Python API 或 ONNX 模型,然后通过 C# 与 Python 或 ONNX 进行交互。

发表回复