OpenCvSharp+Yolov5Net+Onnx 完整Demo
效果
工程
代码
using Microsoft.ML.OnnxRuntime;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace OpenCvSharp_Yolov5Net_Onnx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string PicFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = PicFilter;
if (ofd.ShowDialog() != DialogResult.OK) return;
var imagefile = ofd.FileName;
var image = Image.FromFile(imagefile);
Yolov5Net.Scorer.YoloScorer<Yolov5Net.Scorer.Models.YoloCocoP5Model> scorer = new Yolov5Net.Scorer.YoloScorer<Yolov5Net.Scorer.Models.YoloCocoP5Model>("yolov5s.onnx");
List<Yolov5Net.Scorer.YoloPrediction> predictions = scorer.Predict(image);
var graphics = Graphics.FromImage(image);
foreach (var prediction in predictions) // iterate predictions to draw results
{
double score = Math.Round(prediction.Score, 2);
graphics.DrawRectangles(new Pen(prediction.Label.Color, 2), new[] { prediction.Rectangle });
PointF p = new PointF(prediction.Rectangle.X - 3, prediction.Rectangle.Y - 23);
graphics.DrawString(prediction.Label.Name + " (" + score + ")"
, new Font("Arial", 16, GraphicsUnit.Pixel)
, new SolidBrush(prediction.Label.Color)
, p);
}
pictureBox1.Image = image;
}
FrameSource frame;
Thread t;
private void button2_Click(object sender, EventArgs e)
{
//获取视频设备
frame = Cv2.CreateFrameSource_Camera(0);
t = new Thread(CameraDet);
t.Start();
}
private void CameraDet()
{
Mat mat = new Mat();
//yolov5+onnx检测
var scorer = new Yolov5Net.Scorer.YoloScorer<Yolov5Net.Scorer.Models.YoloCocoP5Model>("yolov5s.onnx");
//逐帧放入
while (true)
{
if (frame.IsDisposed)
{
return;
}
//从摄像头读视频帧
frame.NextFrame(mat);
//先将Mat图像转换成Stream流,再将流转成Bitmap
var image = new Bitmap(mat.ToMemoryStream()) as Image;
//var image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
List<Yolov5Net.Scorer.YoloPrediction> predictions = scorer.Predict(image);
//在图片上绘制目标标识
var graphics = Graphics.FromImage(image);
foreach (var prediction in predictions) // iterate predictions to draw results
{
double score = Math.Round(prediction.Score, 2);
graphics.DrawRectangles(new Pen(prediction.Label.Color, 2),
new[] { prediction.Rectangle });
var (x, y) = (prediction.Rectangle.X - 3, prediction.Rectangle.Y - 23);
graphics.DrawString($"{prediction.Label.Name} ({score})",
new Font("Arial", 16, GraphicsUnit.Pixel), new SolidBrush(prediction.Label.Color),
new PointF(x, y));
pictureBox1.Image = image;
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (frame != null)
{
frame.Dispose();
frame = null;
t.Abort();
}
}
}
}
Demo下载