首页 最新 热门 推荐

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

C# YoloV8 OpenVINO 视频抽帧 自动标注 预标注工具

  • 25-02-19 03:40
  • 2103
  • 10088
blog.csdn.net

C# YoloV8 OpenVINO 视频抽帧 自动标注 预标注工具

目录

效果

项目

代码

下载 


效果

视频抽帧 自动标注 预标注工具 效果

项目

代码

using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

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

        YoloV8 yoloV8;
        YoloV8Async yoloV8Async;

        string model_path;

        string video_path = "";
        string video_name = "";
        string videoFilter = "*.mp4|*.mp4;";
        VideoCapture vcapture;

        string output_path = "";
        string images_path = "";
        string labels_path = "";


        StringBuilder sb = new StringBuilder();

        ///


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

        ///
        ///
        private void Form1_Load(object sender, EventArgs e)
        {
            model_path = "model/yolov8n.onnx";
            yoloV8 = new YoloV8(model_path, "model/lable.txt");

            yoloV8Async = new YoloV8Async(model_path, "model/lable.txt");
        }

        ///


        /// 选择输出目录
        ///

        ///
        ///
        private void button2_Click(object sender, EventArgs e)
        {
            output_path = "";
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                folderBrowserDialog.Description = "选择目录";
                DialogResult dialogResult = folderBrowserDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    output_path = folderBrowserDialog.SelectedPath;

                }
            }
        }

        ///


        /// 选择视频
        ///

        ///
        ///
        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;
            video_name = System.IO.Path.GetFileNameWithoutExtension(video_path);
            textBox1.Text = "";

        }

        ///


        /// 同步接口-视频推理
        ///

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

            if (output_path == "")
            {
                MessageBox.Show("请先选择输出目录!");
                return;
            }

            images_path = output_path + "\\output\\images";
            labels_path = output_path + "\\output\\labels";

            if (!Directory.Exists(images_path))
            {
                Directory.CreateDirectory(images_path);
            }

            if (!Directory.Exists(labels_path))
            {
                Directory.CreateDirectory(labels_path);
            }

            sb.Clear();
            sb.AppendLine($"images path:{images_path}");
            sb.AppendLine($"labels path:{labels_path}");

            textBox1.Text = sb.ToString();

            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;
            }

            Mat frame = new Mat();
            List detResults;

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

            int frameCount = (int)vcapture.Get(VideoCaptureProperties.FrameCount);

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

            int FrameWidth = vcapture.FrameWidth;
            int FrameHeight = vcapture.FrameHeight;
            int index = 0;

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

                _stopwatch.Restart();

                delay = (int)(1000 / videoFps);

                detResults = yoloV8.Detect(frame);

                //输出图片
                Task.Factory.StartNew(() =>
                {
                    Cv2.ImWrite(images_path + "\\" + video_name + "_" + index.ToString() + ".jpg", frame);
                });

                StringBuilder sbLabels = new StringBuilder();
                //绘制结果
                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);

                    //class, x_center, y_center, width, height
                    double width = Math.Round(r.Rect.Width / (double)FrameWidth, 6);
                    double height = Math.Round(r.Rect.Height / (double)FrameHeight, 6);
                    double x_center = Math.Round((r.Rect.Right - (r.Rect.Width / 2)) / (double)FrameWidth, 6);
                    double y_center = Math.Round((r.Rect.Bottom - (r.Rect.Height / 2)) / (double)FrameHeight, 6);

                    sbLabels.Append($"{r.ClassId} {x_center} {y_center} {width} {height}\n");
                }

                //生成不带BOM格式
                using (FileStream fs = new FileStream(labels_path + "\\" + video_name + "_" + index.ToString() + ".txt", FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(false)))
                    {
                        sw.Write(sbLabels.ToString());
                    }
                }
                //Cv2.ImWrite(images_path + "\\" + index.ToString() + ".jpg", frame);
                index++;

                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);
                Cv2.PutText(frame, "progress:" + index.ToString() + "/" + frameCount.ToString(), new OpenCvSharp.Point(10, 270), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);

                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; // 如果按下ESC,退出循环
                }
            }

            Cv2.DestroyAllWindows();
            vcapture.Release();
        }

        ///


        /// 异步接口-视频推理
        ///

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

            if (output_path == "")
            {
                MessageBox.Show("请先选择输出目录!");
                return;
            }

            images_path = output_path + "\\output\\images";
            labels_path = output_path + "\\output\\labels";

            if (!Directory.Exists(images_path))
            {
                Directory.CreateDirectory(images_path);
            }

            if (!Directory.Exists(labels_path))
            {
                Directory.CreateDirectory(labels_path);
            }

            textBox1.Text = "开始异步推理检测";

            Application.DoEvents();

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

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

            textBox1.Text = "异步推理检测完成!";
        }

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

            Mat frame = new Mat();
            List detResults;

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

            int frameCount = (int)vcapture.Get(VideoCaptureProperties.FrameCount);

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

            int FrameWidth = vcapture.FrameWidth;
            int FrameHeight = vcapture.FrameHeight;
            int index = 0;

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

                //输出图片
                Task.Factory.StartNew(() =>
                {
                    Cv2.ImWrite(images_path + "\\" + video_name + "_" + index.ToString() + ".jpg", frame);
                });

                detResults = yoloV8Async.Detect(frame);

                StringBuilder sbLabels = new StringBuilder();
                //绘制结果
                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);

                    //class, x_center, y_center, width, height
                    double width = Math.Round(r.Rect.Width / (double)FrameWidth, 6);
                    double height = Math.Round(r.Rect.Height / (double)FrameHeight, 6);
                    double x_center = Math.Round((r.Rect.Right - (r.Rect.Width / 2)) / (double)FrameWidth, 6);
                    double y_center = Math.Round((r.Rect.Bottom - (r.Rect.Height / 2)) / (double)FrameHeight, 6);

                    sbLabels.Append($"{r.ClassId} {x_center} {y_center} {width} {height}\n");
                }

                //生成不带BOM格式
                using (FileStream fs = new FileStream(labels_path + "\\" + video_name + "_" + index.ToString() + ".txt", FileMode.Create))
                {
                    using (StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(false)))
                    {
                        sw.Write(sbLabels.ToString());
                    }
                }
                //Cv2.ImWrite(images_path + "\\" + index.ToString() + ".jpg", frame);
                index++;

                Cv2.PutText(frame, "preprocessTime:" + yoloV8Async.preprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 30), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "inferTime:" + yoloV8Async.inferTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 70), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "postprocessTime:" + yoloV8Async.postprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 110), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "totalTime:" + yoloV8Async.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:" + yoloV8Async.detFps.ToString("F2"), new OpenCvSharp.Point(10, 230), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
                Cv2.PutText(frame, "progress:" + index.ToString() + "/" + frameCount.ToString(), new OpenCvSharp.Point(10, 270), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);

                //Cv2.ImWrite(images_path + "\\" + index.ToString() + ".jpg", 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; // 如果按下ESC,退出循环
                }
            }
            Cv2.DestroyAllWindows();
            vcapture.Release();
        }
    }
}

  1. using OpenCvSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace yolov8_OpenVINO_Demo
  11. {
  12. public partial class Form2 : Form
  13. {
  14. public Form2()
  15. {
  16. InitializeComponent();
  17. }
  18. YoloV8 yoloV8;
  19. YoloV8Async yoloV8Async;
  20. string model_path;
  21. string video_path = "";
  22. string video_name = "";
  23. string videoFilter = "*.mp4|*.mp4;";
  24. VideoCapture vcapture;
  25. string output_path = "";
  26. string images_path = "";
  27. string labels_path = "";
  28. StringBuilder sb = new StringBuilder();
  29. /// <summary>
  30. /// 窗体加载,初始化
  31. /// </summary>
  32. /// <param name="sender"></param>
  33. /// <param name="e"></param>
  34. private void Form1_Load(object sender, EventArgs e)
  35. {
  36. model_path = "model/yolov8n.onnx";
  37. yoloV8 = new YoloV8(model_path, "model/lable.txt");
  38. yoloV8Async = new YoloV8Async(model_path, "model/lable.txt");
  39. }
  40. /// <summary>
  41. /// 选择输出目录
  42. /// </summary>
  43. /// <param name="sender"></param>
  44. /// <param name="e"></param>
  45. private void button2_Click(object sender, EventArgs e)
  46. {
  47. output_path = "";
  48. using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
  49. {
  50. folderBrowserDialog.Description = "选择目录";
  51. DialogResult dialogResult = folderBrowserDialog.ShowDialog();
  52. if (dialogResult == DialogResult.OK)
  53. {
  54. output_path = folderBrowserDialog.SelectedPath;
  55. }
  56. }
  57. }
  58. /// <summary>
  59. /// 选择视频
  60. /// </summary>
  61. /// <param name="sender"></param>
  62. /// <param name="e"></param>
  63. private void button4_Click(object sender, EventArgs e)
  64. {
  65. OpenFileDialog ofd = new OpenFileDialog();
  66. ofd.Filter = videoFilter;
  67. ofd.InitialDirectory = Application.StartupPath + "\\test";
  68. if (ofd.ShowDialog() != DialogResult.OK) return;
  69. video_path = ofd.FileName;
  70. video_name = System.IO.Path.GetFileNameWithoutExtension(video_path);
  71. textBox1.Text = "";
  72. }
  73. /// <summary>
  74. /// 同步接口-视频推理
  75. /// </summary>
  76. /// <param name="sender"></param>
  77. /// <param name="e"></param>
  78. private void button3_Click(object sender, EventArgs e)
  79. {
  80. if (video_path == "")
  81. {
  82. MessageBox.Show("请先选择视频!");
  83. return;
  84. }
  85. if (output_path == "")
  86. {
  87. MessageBox.Show("请先选择输出目录!");
  88. return;
  89. }
  90. images_path = output_path + "\\output\\images";
  91. labels_path = output_path + "\\output\\labels";
  92. if (!Directory.Exists(images_path))
  93. {
  94. Directory.CreateDirectory(images_path);
  95. }
  96. if (!Directory.Exists(labels_path))
  97. {
  98. Directory.CreateDirectory(labels_path);
  99. }
  100. sb.Clear();
  101. sb.AppendLine($"images path:{images_path}");
  102. sb.AppendLine($"labels path:{labels_path}");
  103. textBox1.Text = sb.ToString();
  104. Application.DoEvents();
  105. Thread thread = new Thread(new ThreadStart(VideoDetection));
  106. thread.Start();
  107. thread.Join();
  108. textBox1.Text = "检测完成!";
  109. }
  110. void VideoDetection()
  111. {
  112. vcapture = new VideoCapture(video_path);
  113. if (!vcapture.IsOpened())
  114. {
  115. MessageBox.Show("打开视频文件失败");
  116. return;
  117. }
  118. Mat frame = new Mat();
  119. List<DetectionResult> detResults;
  120. // 获取视频的fps
  121. double videoFps = vcapture.Get(VideoCaptureProperties.Fps);
  122. // 计算等待时间(毫秒)
  123. int delay = (int)(1000 / videoFps);
  124. Stopwatch _stopwatch = new Stopwatch();
  125. int frameCount = (int)vcapture.Get(VideoCaptureProperties.FrameCount);
  126. Cv2.NamedWindow("DetectionResult 按下ESC,退出", WindowFlags.Normal);
  127. Cv2.ResizeWindow("DetectionResult 按下ESC,退出", vcapture.FrameWidth / 2, vcapture.FrameHeight / 2);
  128. int FrameWidth = vcapture.FrameWidth;
  129. int FrameHeight = vcapture.FrameHeight;
  130. int index = 0;
  131. while (vcapture.Read(frame))
  132. {
  133. if (frame.Empty())
  134. {
  135. MessageBox.Show("读取失败");
  136. return;
  137. }
  138. _stopwatch.Restart();
  139. delay = (int)(1000 / videoFps);
  140. detResults = yoloV8.Detect(frame);
  141. //输出图片
  142. Task.Factory.StartNew(() =>
  143. {
  144. Cv2.ImWrite(images_path + "\\" + video_name + "_" + index.ToString() + ".jpg", frame);
  145. });
  146. StringBuilder sbLabels = new StringBuilder();
  147. //绘制结果
  148. foreach (DetectionResult r in detResults)
  149. {
  150. 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);
  151. Cv2.Rectangle(frame, r.Rect, Scalar.Red, thickness: 2);
  152. //class, x_center, y_center, width, height
  153. double width = Math.Round(r.Rect.Width / (double)FrameWidth, 6);
  154. double height = Math.Round(r.Rect.Height / (double)FrameHeight, 6);
  155. double x_center = Math.Round((r.Rect.Right - (r.Rect.Width / 2)) / (double)FrameWidth, 6);
  156. double y_center = Math.Round((r.Rect.Bottom - (r.Rect.Height / 2)) / (double)FrameHeight, 6);
  157. sbLabels.Append($"{r.ClassId} {x_center} {y_center} {width} {height}\n");
  158. }
  159. //生成不带BOM格式
  160. using (FileStream fs = new FileStream(labels_path + "\\" + video_name + "_" + index.ToString() + ".txt", FileMode.Create))
  161. {
  162. using (StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(false)))
  163. {
  164. sw.Write(sbLabels.ToString());
  165. }
  166. }
  167. //Cv2.ImWrite(images_path + "\\" + index.ToString() + ".jpg", frame);
  168. index++;
  169. Cv2.PutText(frame, "preprocessTime:" + yoloV8.preprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 30), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  170. Cv2.PutText(frame, "inferTime:" + yoloV8.inferTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 70), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  171. Cv2.PutText(frame, "postprocessTime:" + yoloV8.postprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 110), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  172. Cv2.PutText(frame, "totalTime:" + yoloV8.totalTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 150), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  173. Cv2.PutText(frame, "video fps:" + videoFps.ToString("F2"), new OpenCvSharp.Point(10, 190), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  174. Cv2.PutText(frame, "det fps:" + yoloV8.detFps.ToString("F2"), new OpenCvSharp.Point(10, 230), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  175. Cv2.PutText(frame, "progress:" + index.ToString() + "/" + frameCount.ToString(), new OpenCvSharp.Point(10, 270), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  176. Cv2.ImShow("DetectionResult 按下ESC,退出", frame);
  177. //for test
  178. delay = 1;
  179. //delay = (int)(delay - _stopwatch.ElapsedMilliseconds);
  180. //if (delay <= 0)
  181. //{
  182. // delay = 1;
  183. //}
  184. //Console.WriteLine("delay:" + delay.ToString()) ;
  185. if (Cv2.WaitKey(delay) == 27 || Cv2.GetWindowProperty("DetectionResult 按下ESC,退出", WindowPropertyFlags.Visible) < 1.0)
  186. {
  187. Cv2.DestroyAllWindows();
  188. vcapture.Release();
  189. break; // 如果按下ESC,退出循环
  190. }
  191. }
  192. Cv2.DestroyAllWindows();
  193. vcapture.Release();
  194. }
  195. /// <summary>
  196. /// 异步接口-视频推理
  197. /// </summary>
  198. /// <param name="sender"></param>
  199. /// <param name="e"></param>
  200. private void button1_Click(object sender, EventArgs e)
  201. {
  202. if (video_path == "")
  203. {
  204. MessageBox.Show("请先选择视频!");
  205. return;
  206. }
  207. if (output_path == "")
  208. {
  209. MessageBox.Show("请先选择输出目录!");
  210. return;
  211. }
  212. images_path = output_path + "\\output\\images";
  213. labels_path = output_path + "\\output\\labels";
  214. if (!Directory.Exists(images_path))
  215. {
  216. Directory.CreateDirectory(images_path);
  217. }
  218. if (!Directory.Exists(labels_path))
  219. {
  220. Directory.CreateDirectory(labels_path);
  221. }
  222. textBox1.Text = "开始异步推理检测";
  223. Application.DoEvents();
  224. Thread thread = new Thread(new ThreadStart(VideoDetectionAsync));
  225. thread.Start();
  226. thread.Join();
  227. textBox1.Text = "异步推理检测完成!";
  228. }
  229. void VideoDetectionAsync()
  230. {
  231. vcapture = new VideoCapture(video_path);
  232. if (!vcapture.IsOpened())
  233. {
  234. MessageBox.Show("打开视频文件失败");
  235. return;
  236. }
  237. Mat frame = new Mat();
  238. List<DetectionResult> detResults;
  239. // 获取视频的fps
  240. double videoFps = vcapture.Get(VideoCaptureProperties.Fps);
  241. // 计算等待时间(毫秒)
  242. int delay = (int)(1000 / videoFps);
  243. Stopwatch _stopwatch = new Stopwatch();
  244. int frameCount = (int)vcapture.Get(VideoCaptureProperties.FrameCount);
  245. Cv2.NamedWindow("DetectionResult 按下ESC,退出", WindowFlags.Normal);
  246. Cv2.ResizeWindow("DetectionResult 按下ESC,退出", vcapture.FrameWidth / 2, vcapture.FrameHeight / 2);
  247. int FrameWidth = vcapture.FrameWidth;
  248. int FrameHeight = vcapture.FrameHeight;
  249. int index = 0;
  250. while (vcapture.Read(frame))
  251. {
  252. if (frame.Empty())
  253. {
  254. MessageBox.Show("读取失败");
  255. return;
  256. }
  257. //输出图片
  258. Task.Factory.StartNew(() =>
  259. {
  260. Cv2.ImWrite(images_path + "\\" + video_name + "_" + index.ToString() + ".jpg", frame);
  261. });
  262. detResults = yoloV8Async.Detect(frame);
  263. StringBuilder sbLabels = new StringBuilder();
  264. //绘制结果
  265. foreach (DetectionResult r in detResults)
  266. {
  267. 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);
  268. Cv2.Rectangle(frame, r.Rect, Scalar.Red, thickness: 2);
  269. //class, x_center, y_center, width, height
  270. double width = Math.Round(r.Rect.Width / (double)FrameWidth, 6);
  271. double height = Math.Round(r.Rect.Height / (double)FrameHeight, 6);
  272. double x_center = Math.Round((r.Rect.Right - (r.Rect.Width / 2)) / (double)FrameWidth, 6);
  273. double y_center = Math.Round((r.Rect.Bottom - (r.Rect.Height / 2)) / (double)FrameHeight, 6);
  274. sbLabels.Append($"{r.ClassId} {x_center} {y_center} {width} {height}\n");
  275. }
  276. //生成不带BOM格式
  277. using (FileStream fs = new FileStream(labels_path + "\\" + video_name + "_" + index.ToString() + ".txt", FileMode.Create))
  278. {
  279. using (StreamWriter sw = new StreamWriter(fs, new UTF8Encoding(false)))
  280. {
  281. sw.Write(sbLabels.ToString());
  282. }
  283. }
  284. //Cv2.ImWrite(images_path + "\\" + index.ToString() + ".jpg", frame);
  285. index++;
  286. Cv2.PutText(frame, "preprocessTime:" + yoloV8Async.preprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 30), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  287. Cv2.PutText(frame, "inferTime:" + yoloV8Async.inferTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 70), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  288. Cv2.PutText(frame, "postprocessTime:" + yoloV8Async.postprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 110), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  289. Cv2.PutText(frame, "totalTime:" + yoloV8Async.totalTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 150), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  290. Cv2.PutText(frame, "video fps:" + videoFps.ToString("F2"), new OpenCvSharp.Point(10, 190), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  291. Cv2.PutText(frame, "det fps:" + yoloV8Async.detFps.ToString("F2"), new OpenCvSharp.Point(10, 230), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  292. Cv2.PutText(frame, "progress:" + index.ToString() + "/" + frameCount.ToString(), new OpenCvSharp.Point(10, 270), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  293. //Cv2.ImWrite(images_path + "\\" + index.ToString() + ".jpg", frame);
  294. Cv2.ImShow("DetectionResult 按下ESC,退出", frame);
  295. // for test
  296. delay = 1;
  297. //delay = (int)(delay - _stopwatch.ElapsedMilliseconds);
  298. //if (delay <= 0)
  299. //{
  300. // delay = 1;
  301. //}
  302. //Console.WriteLine("delay:" + delay.ToString()) ;
  303. if (Cv2.WaitKey(delay) == 27 || Cv2.GetWindowProperty("DetectionResult 按下ESC,退出", WindowPropertyFlags.Visible) < 1.0)
  304. {
  305. Cv2.DestroyAllWindows();
  306. vcapture.Release();
  307. break; // 如果按下ESC,退出循环
  308. }
  309. }
  310. Cv2.DestroyAllWindows();
  311. vcapture.Release();
  312. }
  313. }
  314. }

下载 

源码下载

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

/ 登录

评论记录:

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

分类栏目

后端 (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