首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

C# YoloV8 模型效果验证工具(OnnxRuntime+ByteTrack推理)

  • 25-02-19 03:40
  • 3638
  • 5886
blog.csdn.net

C# YoloV8 模型效果验证工具(OnnxRuntime+ByteTrack推理)

目录

效果

项目

代码

下载


效果

模型效果验证工具

项目

代码

using ByteTrack;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace C__yolov8_OnnxRuntime_ByteTrack_Demo
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        string imgFilter = "图片|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";

        YoloV8 yoloV8;
        Mat image;

        string image_path = "";
        string model_path;

        string video_path = "";
        string videoFilter = "视频|*.mp4;*.avi;*.dav";
        VideoCapture vcapture;
        VideoWriter vwriter;
        bool saveDetVideo = false;
        ByteTracker tracker;

        ///


        /// 单图推理
        ///

        ///
        ///
        private void button2_Click(object sender, EventArgs e)
        {

            if (image_path == "")
            {
                return;
            }

            button2.Enabled = false;
            pictureBox2.Image = null;
            textBox1.Text = "";

            Application.DoEvents();

            image = new Mat(image_path);

            List detResults = yoloV8.Detect(image);

            //绘制结果
            Mat result_image = image.Clone();
            foreach (DetectionResult r in detResults)
            {
                string info = $"{r.Class}:{r.Confidence:P0}";
                //绘制
                Cv2.PutText(result_image, info, new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.Rectangle(result_image, r.Rect, Scalar.Red, thickness: 2);

            }

            if (pictureBox2.Image != null)
            {
                pictureBox2.Image.Dispose();
            }
            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
            textBox1.Text = yoloV8.DetectTime();

            button2.Enabled = true;

        }

        ///


        /// 窗体加载,初始化
        ///

        ///
        ///
        private void Form1_Load(object sender, EventArgs e)
        {
            image_path = "test/dog.jpg";
            pictureBox1.Image = new Bitmap(image_path);

            model_path = "model/yolov8n.onnx";

            yoloV8 = new YoloV8(model_path, "model/lable.txt");
        }

        ///


        /// 选择图片
        ///

        ///
        ///
        private void button1_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = imgFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;

            pictureBox1.Image = null;

            image_path = ofd.FileName;
            pictureBox1.Image = new Bitmap(image_path);

            textBox1.Text = "";
            pictureBox2.Image = null;
        }

        ///


        /// 选择视频
        ///

        ///
        ///
        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = videoFilter;
            ofd.InitialDirectory = Application.StartupPath + "\\test";
            if (ofd.ShowDialog() != DialogResult.OK) return;

            video_path = ofd.FileName;

            textBox1.Text = video_path;
            //pictureBox1.Image = null;
            //pictureBox2.Image = null;

            //button3_Click(null, null);

        }

        ///


        /// 视频推理
        ///

        ///
        ///
        private void button3_Click(object sender, EventArgs e)
        {
            if (video_path == "")
            {
                MessageBox.Show("请先选择视频!");
                return;
            }

            textBox1.Text = "开始检测";

            Application.DoEvents();

            Thread thread = new Thread(new ThreadStart(VideoDetection));

            thread.Start();
            thread.Join();

            textBox1.Text = "检测完成!";
        }

        void VideoDetection()
        {
            vcapture = new VideoCapture(video_path);
            if (!vcapture.IsOpened())
            {
                MessageBox.Show("打开视频文件失败");
                return;
            }

            tracker = new ByteTracker((int)vcapture.Fps, 200);

            Mat frame = new Mat();
            List detResults;

            // 获取视频的fps
            double videoFps = vcapture.Get(VideoCaptureProperties.Fps);
            // 计算等待时间(毫秒)
            int delay = (int)(1000 / videoFps);
            Stopwatch _stopwatch = new Stopwatch();

            if (checkBox1.Checked)
            {
                vwriter = new VideoWriter("out.mp4", FourCC.X264, vcapture.Fps, new OpenCvSharp.Size(vcapture.FrameWidth, vcapture.FrameHeight));
                saveDetVideo = true;
            }
            else
            {
                saveDetVideo = false;
            }

            Cv2.NamedWindow("DetectionResult 按下ESC,退出", WindowFlags.Normal);
            Cv2.ResizeWindow("DetectionResult 按下ESC,退出", vcapture.FrameWidth / 2, vcapture.FrameHeight / 2);

            while (vcapture.Read(frame))
            {
                if (frame.Empty())
                {
                    MessageBox.Show("读取失败");
                    return;
                }
                Mat mat_temp = frame.Clone();
                _stopwatch.Restart();

                delay = (int)(1000 / videoFps);

                detResults = yoloV8.Detect(frame);

                //绘制结果
                //foreach (DetectionResult r in detResults)
                //{
                //    Cv2.PutText(frame, $"{r.Class}:{r.Confidence:P0}", new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                //    Cv2.Rectangle(frame, r.Rect, Scalar.Red, thickness: 2);
                //}

                Cv2.PutText(frame, "preprocessTime:" + yoloV8.preprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 30), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "inferTime:" + yoloV8.inferTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 70), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "postprocessTime:" + yoloV8.postprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 110), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "totalTime:" + yoloV8.totalTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 150), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "video fps:" + videoFps.ToString("F2"), new OpenCvSharp.Point(10, 190), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "det fps:" + yoloV8.detFps.ToString("F2"), new OpenCvSharp.Point(10, 230), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);

                List track = new List();
                Track temp;
                foreach (DetectionResult r in detResults)
                {
                    RectBox _box = new RectBox(r.Rect.X, r.Rect.Y, r.Rect.Width, r.Rect.Height);
                    temp = new Track(_box, r.Confidence, ("label", r.ClassId), ("name", r.Class));
                    track.Add(temp);
                }

                var trackOutputs = tracker.Update(track);

                foreach (var t in trackOutputs)
                {
                    int x = (int)t.RectBox.X;
                    int y = (int)t.RectBox.Y;
                    int width = (int)t.RectBox.Width;
                    int height = (int)t.RectBox.Height;

                    if (x < 0)
                    {
                        x = 0;
                    }

                    if (y < 0)
                    {
                        y = 0;
                    }

                    if (x + width > mat_temp.Width)
                    {
                        width = mat_temp.Width - x;
                    }

                    if (y + height > mat_temp.Height)
                    {
                        height = mat_temp.Height - y;
                    }

                    Rect rect = new Rect(x, y, width, height);

                    string txt = $"{t["name"]}-{t.TrackId}:{t.Score:P0}";
                    
                    //if (t["name"].ToString() != "Plate" && t["name"].ToString() != "Person")
                    //{
                    //    Mat mat_car = new Mat(mat_temp, rect);
                    //    KeyValuePair cls = yoloV8_Cls.Detect(mat_car);
                    //    mat_car.Dispose();
                    //    txt += $" {cls.Key}:{cls.Value:P0}";
                    //}

                    //string txt = $"{t["name"]}-{t.TrackId}";
                    Cv2.PutText(frame, txt, new OpenCvSharp.Point(rect.TopLeft.X, rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                    Cv2.Rectangle(frame, rect, Scalar.Red, thickness: 2);
                }
                mat_temp.Dispose();


                if (saveDetVideo)
                {
                    vwriter.Write(frame);
                }

                Cv2.ImShow("DetectionResult 按下ESC,退出", frame);

                // for test
                // delay = 1;
                delay = (int)(delay - _stopwatch.ElapsedMilliseconds);
                if (delay <= 0)
                {
                    delay = 1;
                }
                //Console.WriteLine("delay:" + delay.ToString()) ;
                if (Cv2.WaitKey(delay) == 27 || Cv2.GetWindowProperty("DetectionResult 按下ESC,退出", WindowPropertyFlags.Visible) < 1.0)
                {
                    Cv2.DestroyAllWindows();
                    vcapture.Release();
                    break;
                }
            }

            Cv2.DestroyAllWindows();
            vcapture.Release();
            if (saveDetVideo)
            {
                vwriter.Release();
            }

        }

        string model_path1 = "";
        string model_path2 = "";
        string onnxFilter = "onnx模型|*.onnx;";

        private void button5_Click(object sender, EventArgs e)
        {
            if (video_path == "")
            {
                MessageBox.Show("请先选择视频!");
                return;
            }

            if (model_path1 == "")
            {
                MessageBox.Show("选择模型1");
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = onnxFilter;
                ofd.InitialDirectory = Application.StartupPath + "\\model";
                if (ofd.ShowDialog() != DialogResult.OK) return;
                model_path1 = ofd.FileName;
            }

            if (model_path2 == "")
            {
                MessageBox.Show("选择模型2");
                OpenFileDialog ofd1 = new OpenFileDialog();
                ofd1.Filter = onnxFilter;
                ofd1.InitialDirectory = Application.StartupPath + "\\model";
                if (ofd1.ShowDialog() != DialogResult.OK) return;
                model_path2 = ofd1.FileName;
            }

            textBox1.Text = "开始检测";
            Application.DoEvents();

            Task task = new Task(() =>
            {
                VideoCapture vcapture = new VideoCapture(video_path);
                if (!vcapture.IsOpened())
                {
                    MessageBox.Show("打开视频文件失败");
                    return;
                }

                YoloV8_Compare yoloV8 = new YoloV8_Compare(model_path1, model_path2, "model/lable.txt");

                Mat frame = new Mat();

                // 获取视频的fps
                double videoFps = vcapture.Get(VideoCaptureProperties.Fps);
                // 计算等待时间(毫秒)
                int delay = (int)(1000 / videoFps);
                Stopwatch _stopwatch = new Stopwatch();

                Cv2.NamedWindow("DetectionResult 按下ESC,退出", WindowFlags.Normal);
                Cv2.ResizeWindow("DetectionResult 按下ESC,退出", vcapture.FrameWidth, vcapture.FrameHeight / 2);

                while (vcapture.Read(frame))
                {
                    if (frame.Empty())
                    {
                        MessageBox.Show("读取失败");
                        return;
                    }

                    _stopwatch.Restart();

                    delay = (int)(1000 / videoFps);

                    Mat result = yoloV8.Detect(frame, videoFps.ToString("F2"));

                    Cv2.ImShow("DetectionResult 按下ESC,退出", result);

                    // for test
                    // delay = 1;
                    delay = (int)(delay - _stopwatch.ElapsedMilliseconds);
                    if (delay <= 0)
                    {
                        delay = 1;
                    }
                    //Console.WriteLine("delay:" + delay.ToString()) ;
                    // 如果按下ESC或点击关闭,退出循环
                    if (Cv2.WaitKey(delay) == 27 || Cv2.GetWindowProperty("DetectionResult 按下ESC,退出", WindowPropertyFlags.Visible) < 1.0)
                    {
                        Cv2.DestroyAllWindows();
                        vcapture.Release();
                        break;
                    }
                }

                textBox1.Invoke(new Action(() =>
                {
                    textBox1.Text = "检测结束!";

                }));

            });
            task.Start();

        }

        //保存
        SaveFileDialog sdf = new SaveFileDialog();
        private void button6_Click(object sender, EventArgs e)
        {
            if (pictureBox2.Image == null)
            {
                return;
            }
            Bitmap output = new Bitmap(pictureBox2.Image);
            sdf.Title = "保存";
            sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp";
            if (sdf.ShowDialog() == DialogResult.OK)
            {
                switch (sdf.FilterIndex)
                {
                    case 1:
                        {
                            output.Save(sdf.FileName, ImageFormat.Jpeg);
                            break;
                        }
                    case 2:
                        {
                            output.Save(sdf.FileName, ImageFormat.Png);
                            break;
                        }
                    case 3:
                        {
                            output.Save(sdf.FileName, ImageFormat.Bmp);
                            break;
                        }
                }
                MessageBox.Show("保存成功,位置:" + sdf.FileName);
            }

        }

        ///


        /// 选择模型
        ///

        ///
        ///
        private void button7_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = onnxFilter;
            ofd.InitialDirectory = Application.StartupPath + "\\model";
            if (ofd.ShowDialog() != DialogResult.OK) return;
            model_path = ofd.FileName;
            yoloV8 = new YoloV8(model_path, "model/lable.txt");

        }
    }

}

  1. using ByteTrack;
  2. using OpenCvSharp;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.Drawing.Imaging;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using System.Windows.Forms;
  11. namespace C__yolov8_OnnxRuntime_ByteTrack_Demo
  12. {
  13. public partial class Form2 : Form
  14. {
  15. public Form2()
  16. {
  17. InitializeComponent();
  18. }
  19. string imgFilter = "图片|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
  20. YoloV8 yoloV8;
  21. Mat image;
  22. string image_path = "";
  23. string model_path;
  24. string video_path = "";
  25. string videoFilter = "视频|*.mp4;*.avi;*.dav";
  26. VideoCapture vcapture;
  27. VideoWriter vwriter;
  28. bool saveDetVideo = false;
  29. ByteTracker tracker;
  30. /// <summary>
  31. /// 单图推理
  32. /// </summary>
  33. /// <param name="sender"></param>
  34. /// <param name="e"></param>
  35. private void button2_Click(object sender, EventArgs e)
  36. {
  37. if (image_path == "")
  38. {
  39. return;
  40. }
  41. button2.Enabled = false;
  42. pictureBox2.Image = null;
  43. textBox1.Text = "";
  44. Application.DoEvents();
  45. image = new Mat(image_path);
  46. List<DetectionResult> detResults = yoloV8.Detect(image);
  47. //绘制结果
  48. Mat result_image = image.Clone();
  49. foreach (DetectionResult r in detResults)
  50. {
  51. string info = $"{r.Class}:{r.Confidence:P0}";
  52. //绘制
  53. Cv2.PutText(result_image, info, new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  54. Cv2.Rectangle(result_image, r.Rect, Scalar.Red, thickness: 2);
  55. }
  56. if (pictureBox2.Image != null)
  57. {
  58. pictureBox2.Image.Dispose();
  59. }
  60. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  61. textBox1.Text = yoloV8.DetectTime();
  62. button2.Enabled = true;
  63. }
  64. /// <summary>
  65. /// 窗体加载,初始化
  66. /// </summary>
  67. /// <param name="sender"></param>
  68. /// <param name="e"></param>
  69. private void Form1_Load(object sender, EventArgs e)
  70. {
  71. image_path = "test/dog.jpg";
  72. pictureBox1.Image = new Bitmap(image_path);
  73. model_path = "model/yolov8n.onnx";
  74. yoloV8 = new YoloV8(model_path, "model/lable.txt");
  75. }
  76. /// <summary>
  77. /// 选择图片
  78. /// </summary>
  79. /// <param name="sender"></param>
  80. /// <param name="e"></param>
  81. private void button1_Click_1(object sender, EventArgs e)
  82. {
  83. OpenFileDialog ofd = new OpenFileDialog();
  84. ofd.Filter = imgFilter;
  85. if (ofd.ShowDialog() != DialogResult.OK) return;
  86. pictureBox1.Image = null;
  87. image_path = ofd.FileName;
  88. pictureBox1.Image = new Bitmap(image_path);
  89. textBox1.Text = "";
  90. pictureBox2.Image = null;
  91. }
  92. /// <summary>
  93. /// 选择视频
  94. /// </summary>
  95. /// <param name="sender"></param>
  96. /// <param name="e"></param>
  97. private void button4_Click(object sender, EventArgs e)
  98. {
  99. OpenFileDialog ofd = new OpenFileDialog();
  100. ofd.Filter = videoFilter;
  101. ofd.InitialDirectory = Application.StartupPath + "\\test";
  102. if (ofd.ShowDialog() != DialogResult.OK) return;
  103. video_path = ofd.FileName;
  104. textBox1.Text = video_path;
  105. //pictureBox1.Image = null;
  106. //pictureBox2.Image = null;
  107. //button3_Click(null, null);
  108. }
  109. /// <summary>
  110. /// 视频推理
  111. /// </summary>
  112. /// <param name="sender"></param>
  113. /// <param name="e"></param>
  114. private void button3_Click(object sender, EventArgs e)
  115. {
  116. if (video_path == "")
  117. {
  118. MessageBox.Show("请先选择视频!");
  119. return;
  120. }
  121. textBox1.Text = "开始检测";
  122. Application.DoEvents();
  123. Thread thread = new Thread(new ThreadStart(VideoDetection));
  124. thread.Start();
  125. thread.Join();
  126. textBox1.Text = "检测完成!";
  127. }
  128. void VideoDetection()
  129. {
  130. vcapture = new VideoCapture(video_path);
  131. if (!vcapture.IsOpened())
  132. {
  133. MessageBox.Show("打开视频文件失败");
  134. return;
  135. }
  136. tracker = new ByteTracker((int)vcapture.Fps, 200);
  137. Mat frame = new Mat();
  138. List<DetectionResult> detResults;
  139. // 获取视频的fps
  140. double videoFps = vcapture.Get(VideoCaptureProperties.Fps);
  141. // 计算等待时间(毫秒)
  142. int delay = (int)(1000 / videoFps);
  143. Stopwatch _stopwatch = new Stopwatch();
  144. if (checkBox1.Checked)
  145. {
  146. vwriter = new VideoWriter("out.mp4", FourCC.X264, vcapture.Fps, new OpenCvSharp.Size(vcapture.FrameWidth, vcapture.FrameHeight));
  147. saveDetVideo = true;
  148. }
  149. else
  150. {
  151. saveDetVideo = false;
  152. }
  153. Cv2.NamedWindow("DetectionResult 按下ESC,退出", WindowFlags.Normal);
  154. Cv2.ResizeWindow("DetectionResult 按下ESC,退出", vcapture.FrameWidth / 2, vcapture.FrameHeight / 2);
  155. while (vcapture.Read(frame))
  156. {
  157. if (frame.Empty())
  158. {
  159. MessageBox.Show("读取失败");
  160. return;
  161. }
  162. Mat mat_temp = frame.Clone();
  163. _stopwatch.Restart();
  164. delay = (int)(1000 / videoFps);
  165. detResults = yoloV8.Detect(frame);
  166. //绘制结果
  167. //foreach (DetectionResult r in detResults)
  168. //{
  169. // Cv2.PutText(frame, $"{r.Class}:{r.Confidence:P0}", new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  170. // Cv2.Rectangle(frame, r.Rect, Scalar.Red, thickness: 2);
  171. //}
  172. Cv2.PutText(frame, "preprocessTime:" + yoloV8.preprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 30), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  173. Cv2.PutText(frame, "inferTime:" + yoloV8.inferTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 70), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  174. Cv2.PutText(frame, "postprocessTime:" + yoloV8.postprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 110), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  175. Cv2.PutText(frame, "totalTime:" + yoloV8.totalTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 150), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  176. Cv2.PutText(frame, "video fps:" + videoFps.ToString("F2"), new OpenCvSharp.Point(10, 190), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  177. Cv2.PutText(frame, "det fps:" + yoloV8.detFps.ToString("F2"), new OpenCvSharp.Point(10, 230), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  178. List<Track> track = new List<Track>();
  179. Track temp;
  180. foreach (DetectionResult r in detResults)
  181. {
  182. RectBox _box = new RectBox(r.Rect.X, r.Rect.Y, r.Rect.Width, r.Rect.Height);
  183. temp = new Track(_box, r.Confidence, ("label", r.ClassId), ("name", r.Class));
  184. track.Add(temp);
  185. }
  186. var trackOutputs = tracker.Update(track);
  187. foreach (var t in trackOutputs)
  188. {
  189. int x = (int)t.RectBox.X;
  190. int y = (int)t.RectBox.Y;
  191. int width = (int)t.RectBox.Width;
  192. int height = (int)t.RectBox.Height;
  193. if (x < 0)
  194. {
  195. x = 0;
  196. }
  197. if (y < 0)
  198. {
  199. y = 0;
  200. }
  201. if (x + width > mat_temp.Width)
  202. {
  203. width = mat_temp.Width - x;
  204. }
  205. if (y + height > mat_temp.Height)
  206. {
  207. height = mat_temp.Height - y;
  208. }
  209. Rect rect = new Rect(x, y, width, height);
  210. string txt = $"{t["name"]}-{t.TrackId}:{t.Score:P0}";
  211. //if (t["name"].ToString() != "Plate" && t["name"].ToString() != "Person")
  212. //{
  213. // Mat mat_car = new Mat(mat_temp, rect);
  214. // KeyValuePair<string, float> cls = yoloV8_Cls.Detect(mat_car);
  215. // mat_car.Dispose();
  216. // txt += $" {cls.Key}:{cls.Value:P0}";
  217. //}
  218. //string txt = $"{t["name"]}-{t.TrackId}";
  219. Cv2.PutText(frame, txt, new OpenCvSharp.Point(rect.TopLeft.X, rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  220. Cv2.Rectangle(frame, rect, Scalar.Red, thickness: 2);
  221. }
  222. mat_temp.Dispose();
  223. if (saveDetVideo)
  224. {
  225. vwriter.Write(frame);
  226. }
  227. Cv2.ImShow("DetectionResult 按下ESC,退出", frame);
  228. // for test
  229. // delay = 1;
  230. delay = (int)(delay - _stopwatch.ElapsedMilliseconds);
  231. if (delay <= 0)
  232. {
  233. delay = 1;
  234. }
  235. //Console.WriteLine("delay:" + delay.ToString()) ;
  236. if (Cv2.WaitKey(delay) == 27 || Cv2.GetWindowProperty("DetectionResult 按下ESC,退出", WindowPropertyFlags.Visible) < 1.0)
  237. {
  238. Cv2.DestroyAllWindows();
  239. vcapture.Release();
  240. break;
  241. }
  242. }
  243. Cv2.DestroyAllWindows();
  244. vcapture.Release();
  245. if (saveDetVideo)
  246. {
  247. vwriter.Release();
  248. }
  249. }
  250. string model_path1 = "";
  251. string model_path2 = "";
  252. string onnxFilter = "onnx模型|*.onnx;";
  253. private void button5_Click(object sender, EventArgs e)
  254. {
  255. if (video_path == "")
  256. {
  257. MessageBox.Show("请先选择视频!");
  258. return;
  259. }
  260. if (model_path1 == "")
  261. {
  262. MessageBox.Show("选择模型1");
  263. OpenFileDialog ofd = new OpenFileDialog();
  264. ofd.Filter = onnxFilter;
  265. ofd.InitialDirectory = Application.StartupPath + "\\model";
  266. if (ofd.ShowDialog() != DialogResult.OK) return;
  267. model_path1 = ofd.FileName;
  268. }
  269. if (model_path2 == "")
  270. {
  271. MessageBox.Show("选择模型2");
  272. OpenFileDialog ofd1 = new OpenFileDialog();
  273. ofd1.Filter = onnxFilter;
  274. ofd1.InitialDirectory = Application.StartupPath + "\\model";
  275. if (ofd1.ShowDialog() != DialogResult.OK) return;
  276. model_path2 = ofd1.FileName;
  277. }
  278. textBox1.Text = "开始检测";
  279. Application.DoEvents();
  280. Task task = new Task(() =>
  281. {
  282. VideoCapture vcapture = new VideoCapture(video_path);
  283. if (!vcapture.IsOpened())
  284. {
  285. MessageBox.Show("打开视频文件失败");
  286. return;
  287. }
  288. YoloV8_Compare yoloV8 = new YoloV8_Compare(model_path1, model_path2, "model/lable.txt");
  289. Mat frame = new Mat();
  290. // 获取视频的fps
  291. double videoFps = vcapture.Get(VideoCaptureProperties.Fps);
  292. // 计算等待时间(毫秒)
  293. int delay = (int)(1000 / videoFps);
  294. Stopwatch _stopwatch = new Stopwatch();
  295. Cv2.NamedWindow("DetectionResult 按下ESC,退出", WindowFlags.Normal);
  296. Cv2.ResizeWindow("DetectionResult 按下ESC,退出", vcapture.FrameWidth, vcapture.FrameHeight / 2);
  297. while (vcapture.Read(frame))
  298. {
  299. if (frame.Empty())
  300. {
  301. MessageBox.Show("读取失败");
  302. return;
  303. }
  304. _stopwatch.Restart();
  305. delay = (int)(1000 / videoFps);
  306. Mat result = yoloV8.Detect(frame, videoFps.ToString("F2"));
  307. Cv2.ImShow("DetectionResult 按下ESC,退出", result);
  308. // for test
  309. // delay = 1;
  310. delay = (int)(delay - _stopwatch.ElapsedMilliseconds);
  311. if (delay <= 0)
  312. {
  313. delay = 1;
  314. }
  315. //Console.WriteLine("delay:" + delay.ToString()) ;
  316. // 如果按下ESC或点击关闭,退出循环
  317. if (Cv2.WaitKey(delay) == 27 || Cv2.GetWindowProperty("DetectionResult 按下ESC,退出", WindowPropertyFlags.Visible) < 1.0)
  318. {
  319. Cv2.DestroyAllWindows();
  320. vcapture.Release();
  321. break;
  322. }
  323. }
  324. textBox1.Invoke(new Action(() =>
  325. {
  326. textBox1.Text = "检测结束!";
  327. }));
  328. });
  329. task.Start();
  330. }
  331. //保存
  332. SaveFileDialog sdf = new SaveFileDialog();
  333. private void button6_Click(object sender, EventArgs e)
  334. {
  335. if (pictureBox2.Image == null)
  336. {
  337. return;
  338. }
  339. Bitmap output = new Bitmap(pictureBox2.Image);
  340. sdf.Title = "保存";
  341. sdf.Filter = "Images (*.jpg)|*.jpg|Images (*.png)|*.png|Images (*.bmp)|*.bmp";
  342. if (sdf.ShowDialog() == DialogResult.OK)
  343. {
  344. switch (sdf.FilterIndex)
  345. {
  346. case 1:
  347. {
  348. output.Save(sdf.FileName, ImageFormat.Jpeg);
  349. break;
  350. }
  351. case 2:
  352. {
  353. output.Save(sdf.FileName, ImageFormat.Png);
  354. break;
  355. }
  356. case 3:
  357. {
  358. output.Save(sdf.FileName, ImageFormat.Bmp);
  359. break;
  360. }
  361. }
  362. MessageBox.Show("保存成功,位置:" + sdf.FileName);
  363. }
  364. }
  365. /// <summary>
  366. /// 选择模型
  367. /// </summary>
  368. /// <param name="sender"></param>
  369. /// <param name="e"></param>
  370. private void button7_Click(object sender, EventArgs e)
  371. {
  372. OpenFileDialog ofd = new OpenFileDialog();
  373. ofd.Filter = onnxFilter;
  374. ofd.InitialDirectory = Application.StartupPath + "\\model";
  375. if (ofd.ShowDialog() != DialogResult.OK) return;
  376. model_path = ofd.FileName;
  377. yoloV8 = new YoloV8(model_path, "model/lable.txt");
  378. }
  379. }
  380. }

下载

源码下载

天天代码码天天
微信公众号
.NET 人工智能实践
注:本文转载自blog.csdn.net的天天代码码天天的文章"https://lw112190.blog.csdn.net/article/details/140024005"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top