本文介紹如何在 ML.NET 中使用 YOLOv7 的 ONNX 模型來檢測圖像中的對象。
什么是 YOLO
YOLO(You Only Look Once)是一種先進的實時目標檢測系統。它是一個在COCO數據集上預訓練的物體檢測架構和模型系列,其版本也是在不斷優化更新。2022年7月,YOLOv7 來臨。官方版的YOLOv7相同體量下比YOLOv5 精度更高,速度更快。
論文地址:https://arxiv.org/abs/2207.02696
ONNX 模型
開放神經網絡交換 (ONNX) 是 AI 模型的開放源代碼格式。ONNX 支持框架之間的互操作性,常見的機器學習框架都支持該模型的使用。
YOLOv7 的模型我們可以從一作 Chien-Yao Wang 的倉庫獲取:https://github.com/WongKinYiu/yolov7。在 Releases v0.1 中提供的 onnx 不能直接使用,我們需要下載預訓練的?yolov7.pt
?然后克隆項目,使用導出工具自行導出 onnx 模型。
python export.py --weights=yolov7.pt --grid --simplify
導出完成我們就可以得到?yolov7.onnx
?,你也可以直接前往?CSDN 下載我分享的文件[1]。
執行預測
1.首先創建控制臺應用程序,選擇 .NET 6 作為要使用的框架。2.安裝?Microsoft.ML.OnnxTransformer
?NuGet 包3.YOLOv7 整體結構與 YOLOv5 極其相似,我們可以直接使用?Yolov5Net
?NuGet 包里的分析器來處理模型輸出。
剩下的工作,我們只需要編寫執行預測的代碼即可:
static readonly string assetsPath = GetAbsolutePath(@"../../../assets");
static readonly string modelFilePath = Path.Combine(assetsPath, "Model", "yolov7.onnx");
static readonly string imagesFolder = Path.Combine(assetsPath, "images");
static readonly string outputFolder = Path.Combine(assetsPath, "images", "output");private static void Main(string[] args)
{if (!Directory.Exists(outputFolder)){Directory.CreateDirectory(outputFolder);}var imgs = Directory.GetFiles(imagesFolder).Where(filePath => Path.GetExtension(filePath) == ".jpg");using var scorer = new YoloScorer<YoloCocoP5Model>(modelFilePath);foreach (var imgsFile in imgs){using var image = Image.FromFile(imgsFile);List<YoloPrediction> predictions = scorer.Predict(image);using var graphics = Graphics.FromImage(image);foreach (var prediction in predictions){double score = Math.Round(prediction.Score, 2);graphics.DrawRectangles(new Pen(prediction.Label.Color, 3),new[] { prediction.Rectangle });var (x, y) = (prediction.Rectangle.X - 3, prediction.Rectangle.Y - 23);graphics.DrawString($"{prediction.Label.Name} ({score})",new Font("Consolas", 16, GraphicsUnit.Pixel), new SolidBrush(prediction.Label.Color),new PointF(x, y));}image.Save(Path.Combine(outputFolder, $"result{DateTime.Now.Ticks}.jpg"));}
}/// <summary>
/// 獲取程序啟動目錄
/// </summary>
/// <param name="relativePath">之下的某個路徑</param>
/// <returns></returns>
private static string GetAbsolutePath(string relativePath)
{FileInfo _dataRoot = new FileInfo(typeof(Program).Assembly.Location);string assemblyFolderPath = _dataRoot.Directory!.FullName;string fullPath = Path.Combine(assemblyFolderPath, relativePath);return fullPath;
}
完整的代碼樣例見:https://github.com/sangyuxiaowu/ml_yolov7
編寫完成執行,然后我們就可以在?assets/images/output
?目錄看到樣例圖片的預測結果:
示例和參考
微軟官方提供了?在 ML.NET 中使用 ONNX 檢測對象[2]?的更詳細的教程,包含訓練和預測,感興趣的同學可前往查閱。
References
[1]
?CSDN 下載我分享的文件:?https://download.csdn.net/download/marin1993/86912472[2]
?在 ML.NET 中使用 ONNX 檢測對象:?https://learn.microsoft.com/zh-cn/dotnet/machine-learning/tutorials/object-detection-onnx