共计 3296 个字符,预计需要花费 9 分钟才能阅读完成。
技术背景
YOLOv8 是 Ultralytics 公司推出的最新目标检测模型,相比前代速度更快、精度更高。它的优势在于:

- 单阶段检测架构,推理速度极快(实时性优势)
- 支持分类、检测、分割多任务
- 提供从 Nano 到 XLarge 多种尺寸预训练模型
- 完善的 Python 生态和文档支持
环境准备
Python 环境
- 安装 Miniconda(推荐)或原生 Python 3.8+
- 创建虚拟环境:
conda create -n yolov8 python=3.8 conda activate yolov8 - 安装 Ultralytics 包:
pip install ultralytics
.NET 环境
- 推荐使用 .NET 6 或更高版本
- Visual Studio 2022(社区版即可)
必要 NuGet 包
Install-Package Microsoft.ML
Install-Package Microsoft.ML.OnnxRuntime
Install-Package SixLabors.ImageSharp # 用于图像处理
模型准备
导出 ONNX 模型
- 准备 Python 脚本
export.py:from ultralytics import YOLO model = YOLO('yolov8n.pt') # 加载官方预训练模型 model.export(format='onnx') # 默认导出到同级目录 - 执行导出:
python export.py
模型输入输出说明
- 输入:
float32[1, 3, 640, 640]归一化后的 RGB 图像张量 - 输出:
float32[1, 84, 8400]检测结果(YOLOv8 无锚框设计)
C# 实现
图像预处理
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
public static float[] PreprocessImage(string imagePath)
{
// 加载图像并调整尺寸
using var image = Image.Load<Rgb24>(imagePath);
image.Mutate(x => x.Resize(640, 640));
// 转换为归一化张量
var tensor = new float[1 * 3 * 640 * 640];
int index = 0;
for (int y = 0; y < image.Height; y++)
{for (int x = 0; x < image.Width; x++)
{var pixel = image[x, y];
tensor[index] = pixel.R / 255f; // R 通道
tensor[index + 1] = pixel.G / 255f; // G 通道
tensor[index + 2] = pixel.B / 255f; // B 通道
index += 3;
}
}
return tensor;
}
ONNX 模型推理
using Microsoft.ML;
using Microsoft.ML.Transforms.Onnx;
var mlContext = new MLContext();
// 创建推理管道
var pipeline = mlContext.Transforms
.ApplyOnnxModel(
modelFile: "yolov8n.onnx",
shapeDictionary: new Dictionary<string, int[]>
{{ "images", new[] {1, 3, 640, 640} },
{"output0", new[] {1, 84, 8400} }
});
// 创建预测引擎
var emptyData = mlContext.Data.LoadFromEnumerable(new List<InputData>());
var model = pipeline.Fit(emptyData);
var predictionEngine = mlContext.Model.CreatePredictionEngine<InputData, OutputData>(model);
// 执行推理
var input = new InputData {Data = PreprocessImage("test.jpg") };
var output = predictionEngine.Predict(input);
后处理代码
public class DetectionResult
{public float X { get; set;}
public float Y {get; set;}
public float Width {get; set;}
public float Height {get; set;}
public float Confidence {get; set;}
public int ClassId {get; set;}
public string ClassName {get; set;}
}
public List<DetectionResult> ProcessOutput(float[] output, float confidenceThreshold = 0.5f)
{var results = new List<DetectionResult>();
// YOLOv8 输出格式解析
for (int i = 0; i < 8400; i++)
{
// 获取最大置信度的类别
int classId = 0;
float maxConfidence = 0;
for (int j = 4; j < 84; j++)
{float confidence = output[i * 84 + j];
if (confidence > maxConfidence)
{
maxConfidence = confidence;
classId = j - 4;
}
}
// 应用置信度阈值
float boxConfidence = output[i * 84 + 4 + classId];
if (boxConfidence > confidenceThreshold)
{
results.Add(new DetectionResult
{X = output[i * 84],
Y = output[i * 84 + 1],
Width = output[i * 84 + 2],
Height = output[i * 84 + 3],
Confidence = boxConfidence,
ClassId = classId
});
}
}
// 非极大值抑制 (NMS)
return ApplyNMS(results);
}
性能优化
多线程处理
// 使用 Parallel.For 处理多张图片
Parallel.For(0, imagePaths.Length, i =>
{var input = new InputData { Data = PreprocessImage(imagePaths[i]) };
var output = predictionEngine.Predict(input);
// ... 后处理代码
});
GPU 加速
- 安装 GPU 版 ONNX Runtime:
Install-Package Microsoft.ML.OnnxRuntime.Gpu - 创建 SessionOptions 时指定 GPU:
var sessionOptions = new SessionOptions(); sessionOptions.AppendExecutionProvider_CUDA();
常见问题
模型尺寸与速度权衡
- YOLOv8n(nano):2.4MB,适合移动端
- YOLOv8s(small):11.4MB,平衡之选
- YOLOv8m(medium):25.9MB,精度优先
内存泄漏预防
- 及时释放预测引擎:
predictionEngine.Dispose(); - 使用
using语句管理图像资源
跨平台部署
- ONNX 模型兼容 Windows/Linux/macOS
- ARM 设备需使用 ONNX Runtime ARM 版本
进阶建议
自定义数据集训练
- 准备 COCO 格式数据集
- 修改 YOLOv8 配置文件
- 执行训练命令:
model.train(data="coco128.yaml", epochs=100)
模型量化
model.export(format='onnx', int8=True) # 8 位整数量化
进一步学习
正文完
