首页 最新 热门 推荐

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

C# yolov8 OpenVINO+ByteTrack Demo

  • 25-02-19 03:20
  • 3633
  • 5929
blog.csdn.net

C# yolov8 OpenVINO+ByteTrack Demo

目录

效果

项目

代码

Form2.cs

YoloV8.cs

ByteTracker.cs

下载

参考 


效果

项目

​

代码

Form2.cs

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


namespace yolov8_OpenVINO_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|*.mp4;";
        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)
            {
                Cv2.PutText(result_image, $"{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(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 = "";
            pictureBox1.Image = null;
            pictureBox2.Image = null;

            button3_Click(null, null);

        }

        ///


        /// 视频推理
        ///

        ///
        ///
        private void button3_Click(object sender, EventArgs e)
        {
            if (video_path == "")
            {
                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;
                }

                _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)
                {
                    Rect rect = new Rect((int)t.RectBox.X, (int)t.RectBox.Y, (int)t.RectBox.Width, (int)t.RectBox.Height);
                    //string txt = $"{t["name"]}-{t.TrackId}:{t.Score: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);
                }

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

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

        }

    }

}
 

  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.Threading;
  8. using System.Windows.Forms;
  9. namespace yolov8_OpenVINO_Demo
  10. {
  11. public partial class Form2 : Form
  12. {
  13. public Form2()
  14. {
  15. InitializeComponent();
  16. }
  17. string imgFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
  18. YoloV8 yoloV8;
  19. Mat image;
  20. string image_path = "";
  21. string model_path;
  22. string video_path = "";
  23. string videoFilter = "*.mp4|*.mp4;";
  24. VideoCapture vcapture;
  25. VideoWriter vwriter;
  26. bool saveDetVideo = false;
  27. ByteTracker tracker;
  28. /// <summary>
  29. /// 单图推理
  30. /// </summary>
  31. /// <param name="sender"></param>
  32. /// <param name="e"></param>
  33. private void button2_Click(object sender, EventArgs e)
  34. {
  35. if (image_path == "")
  36. {
  37. return;
  38. }
  39. button2.Enabled = false;
  40. pictureBox2.Image = null;
  41. textBox1.Text = "";
  42. Application.DoEvents();
  43. image = new Mat(image_path);
  44. List<DetectionResult> detResults = yoloV8.Detect(image);
  45. //绘制结果
  46. Mat result_image = image.Clone();
  47. foreach (DetectionResult r in detResults)
  48. {
  49. Cv2.PutText(result_image, $"{r.Class}:{r.Confidence:P0}", new OpenCvSharp.Point(r.Rect.TopLeft.X, r.Rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  50. Cv2.Rectangle(result_image, r.Rect, Scalar.Red, thickness: 2);
  51. }
  52. if (pictureBox2.Image != null)
  53. {
  54. pictureBox2.Image.Dispose();
  55. }
  56. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  57. textBox1.Text = yoloV8.DetectTime();
  58. button2.Enabled = true;
  59. }
  60. /// <summary>
  61. /// 窗体加载,初始化
  62. /// </summary>
  63. /// <param name="sender"></param>
  64. /// <param name="e"></param>
  65. private void Form1_Load(object sender, EventArgs e)
  66. {
  67. image_path = "test/dog.jpg";
  68. pictureBox1.Image = new Bitmap(image_path);
  69. model_path = "model/yolov8n.onnx";
  70. yoloV8 = new YoloV8(model_path, "model/lable.txt");
  71. }
  72. /// <summary>
  73. /// 选择图片
  74. /// </summary>
  75. /// <param name="sender"></param>
  76. /// <param name="e"></param>
  77. private void button1_Click_1(object sender, EventArgs e)
  78. {
  79. OpenFileDialog ofd = new OpenFileDialog();
  80. ofd.Filter = imgFilter;
  81. if (ofd.ShowDialog() != DialogResult.OK) return;
  82. pictureBox1.Image = null;
  83. image_path = ofd.FileName;
  84. pictureBox1.Image = new Bitmap(image_path);
  85. textBox1.Text = "";
  86. pictureBox2.Image = null;
  87. }
  88. /// <summary>
  89. /// 选择视频
  90. /// </summary>
  91. /// <param name="sender"></param>
  92. /// <param name="e"></param>
  93. private void button4_Click(object sender, EventArgs e)
  94. {
  95. OpenFileDialog ofd = new OpenFileDialog();
  96. ofd.Filter = videoFilter;
  97. ofd.InitialDirectory = Application.StartupPath + "\\test";
  98. if (ofd.ShowDialog() != DialogResult.OK) return;
  99. video_path = ofd.FileName;
  100. textBox1.Text = "";
  101. pictureBox1.Image = null;
  102. pictureBox2.Image = null;
  103. button3_Click(null, null);
  104. }
  105. /// <summary>
  106. /// 视频推理
  107. /// </summary>
  108. /// <param name="sender"></param>
  109. /// <param name="e"></param>
  110. private void button3_Click(object sender, EventArgs e)
  111. {
  112. if (video_path == "")
  113. {
  114. return;
  115. }
  116. textBox1.Text = "开始检测";
  117. Application.DoEvents();
  118. Thread thread = new Thread(new ThreadStart(VideoDetection));
  119. thread.Start();
  120. thread.Join();
  121. textBox1.Text = "检测完成!";
  122. }
  123. void VideoDetection()
  124. {
  125. vcapture = new VideoCapture(video_path);
  126. if (!vcapture.IsOpened())
  127. {
  128. MessageBox.Show("打开视频文件失败");
  129. return;
  130. }
  131. tracker = new ByteTracker((int)vcapture.Fps, 200);
  132. Mat frame = new Mat();
  133. List<DetectionResult> detResults;
  134. // 获取视频的fps
  135. double videoFps = vcapture.Get(VideoCaptureProperties.Fps);
  136. // 计算等待时间(毫秒)
  137. int delay = (int)(1000 / videoFps);
  138. Stopwatch _stopwatch = new Stopwatch();
  139. if (checkBox1.Checked)
  140. {
  141. vwriter = new VideoWriter("out.mp4", FourCC.X264, vcapture.Fps, new OpenCvSharp.Size(vcapture.FrameWidth, vcapture.FrameHeight));
  142. saveDetVideo = true;
  143. }
  144. else
  145. {
  146. saveDetVideo = false;
  147. }
  148. Cv2.NamedWindow("DetectionResult 按下ESC,退出", WindowFlags.Normal);
  149. Cv2.ResizeWindow("DetectionResult 按下ESC,退出", vcapture.FrameWidth / 2, vcapture.FrameHeight / 2);
  150. while (vcapture.Read(frame))
  151. {
  152. if (frame.Empty())
  153. {
  154. MessageBox.Show("读取失败");
  155. return;
  156. }
  157. _stopwatch.Restart();
  158. delay = (int)(1000 / videoFps);
  159. detResults = yoloV8.Detect(frame);
  160. //绘制结果
  161. //foreach (DetectionResult r in detResults)
  162. //{
  163. // 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);
  164. // Cv2.Rectangle(frame, r.Rect, Scalar.Red, thickness: 2);
  165. //}
  166. Cv2.PutText(frame, "preprocessTime:" + yoloV8.preprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 30), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  167. Cv2.PutText(frame, "inferTime:" + yoloV8.inferTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 70), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  168. Cv2.PutText(frame, "postprocessTime:" + yoloV8.postprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 110), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  169. Cv2.PutText(frame, "totalTime:" + yoloV8.totalTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 150), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  170. Cv2.PutText(frame, "video fps:" + videoFps.ToString("F2"), new OpenCvSharp.Point(10, 190), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  171. Cv2.PutText(frame, "det fps:" + yoloV8.detFps.ToString("F2"), new OpenCvSharp.Point(10, 230), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  172. List<Track> track = new List<Track>();
  173. Track temp;
  174. foreach (DetectionResult r in detResults)
  175. {
  176. RectBox _box = new RectBox(r.Rect.X, r.Rect.Y, r.Rect.Width, r.Rect.Height);
  177. temp = new Track(_box, r.Confidence, ("label", r.ClassId), ("name", r.Class));
  178. track.Add(temp);
  179. }
  180. var trackOutputs = tracker.Update(track);
  181. foreach (var t in trackOutputs)
  182. {
  183. Rect rect = new Rect((int)t.RectBox.X, (int)t.RectBox.Y, (int)t.RectBox.Width, (int)t.RectBox.Height);
  184. //string txt = $"{t["name"]}-{t.TrackId}:{t.Score:P0}";
  185. string txt = $"{t["name"]}-{t.TrackId}";
  186. Cv2.PutText(frame, txt, new OpenCvSharp.Point(rect.TopLeft.X, rect.TopLeft.Y - 10), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  187. Cv2.Rectangle(frame, rect, Scalar.Red, thickness: 2);
  188. }
  189. if (saveDetVideo)
  190. {
  191. vwriter.Write(frame);
  192. }
  193. Cv2.ImShow("DetectionResult 按下ESC,退出", frame);
  194. // for test
  195. // delay = 1;
  196. delay = (int)(delay - _stopwatch.ElapsedMilliseconds);
  197. if (delay <= 0)
  198. {
  199. delay = 1;
  200. }
  201. //Console.WriteLine("delay:" + delay.ToString()) ;
  202. if (Cv2.WaitKey(delay) == 27)
  203. {
  204. break; // 如果按下ESC,退出循环
  205. }
  206. }
  207. Cv2.DestroyAllWindows();
  208. vcapture.Release();
  209. if (saveDetVideo)
  210. {
  211. vwriter.Release();
  212. }
  213. }
  214. }
  215. }

YoloV8.cs

  1. using OpenCvSharp;
  2. using OpenCvSharp.Dnn;
  3. using Sdcb.OpenVINO;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text;
  10. namespace yolov8_OpenVINO_Demo
  11. {
  12. public class YoloV8
  13. {
  14. float[] input_tensor_data;
  15. float[] outputData;
  16. List<DetectionResult> detectionResults;
  17. int input_height;
  18. int input_width;
  19. InferRequest ir;
  20. public string[] class_names;
  21. int class_num;
  22. int box_num;
  23. float conf_threshold;
  24. float nms_threshold;
  25. float ratio_height;
  26. float ratio_width;
  27. public double preprocessTime;
  28. public double inferTime;
  29. public double postprocessTime;
  30. public double totalTime;
  31. public double detFps;
  32. public String DetectTime()
  33. {
  34. StringBuilder stringBuilder = new StringBuilder();
  35. stringBuilder.AppendLine($"Preprocess: {preprocessTime:F2}ms");
  36. stringBuilder.AppendLine($"Infer: {inferTime:F2}ms");
  37. stringBuilder.AppendLine($"Postprocess: {postprocessTime:F2}ms");
  38. stringBuilder.AppendLine($"Total: {totalTime:F2}ms");
  39. return stringBuilder.ToString();
  40. }
  41. public YoloV8(string model_path, string classer_path)
  42. {
  43. Model rawModel = OVCore.Shared.ReadModel(model_path);
  44. PrePostProcessor pp = rawModel.CreatePrePostProcessor();
  45. PreProcessInputInfo inputInfo = pp.Inputs.Primary;
  46. // inputInfo.TensorInfo.Layout = Sdcb.OpenVINO.Layout.NHWC;
  47. // inputInfo.ModelInfo.Layout = Sdcb.OpenVINO.Layout.NCHW;
  48. Model m = pp.BuildModel();
  49. CompiledModel cm = OVCore.Shared.CompileModel(m, "AUTO");
  50. ir = cm.CreateInferRequest();
  51. class_names = File.ReadAllLines(classer_path, Encoding.UTF8);
  52. class_num = class_names.Length;
  53. input_height = 640;
  54. input_width = 640;
  55. box_num = 8400;
  56. conf_threshold = 0.5f;
  57. nms_threshold = 0.5f;
  58. detectionResults = new List<DetectionResult>();
  59. }
  60. void Preprocess(Mat image)
  61. {
  62. //图片缩放
  63. int height = image.Rows;
  64. int width = image.Cols;
  65. Mat temp_image = image.Clone();
  66. if (height > input_height || width > input_width)
  67. {
  68. float scale = Math.Min((float)input_height / height, (float)input_width / width);
  69. OpenCvSharp.Size new_size = new OpenCvSharp.Size((int)(width * scale), (int)(height * scale));
  70. Cv2.Resize(image, temp_image, new_size);
  71. }
  72. ratio_height = (float)height / temp_image.Rows;
  73. ratio_width = (float)width / temp_image.Cols;
  74. Mat input_img = new Mat();
  75. Cv2.CopyMakeBorder(temp_image, input_img, 0, input_height - temp_image.Rows, 0, input_width - temp_image.Cols, BorderTypes.Constant, 0);
  76. //归一化
  77. input_img.ConvertTo(input_img, MatType.CV_32FC3, 1.0 / 255);
  78. input_tensor_data = Common.ExtractMat(input_img);
  79. input_img.Dispose();
  80. temp_image.Dispose();
  81. }
  82. void Postprocess(float[] outputData)
  83. {
  84. detectionResults.Clear();
  85. float[] data = Common.Transpose(outputData, class_num + 4, box_num);
  86. float[] confidenceInfo = new float[class_num];
  87. float[] rectData = new float[4];
  88. List<DetectionResult> detResults = new List<DetectionResult>();
  89. for (int i = 0; i < box_num; i++)
  90. {
  91. Array.Copy(data, i * (class_num + 4), rectData, 0, 4);
  92. Array.Copy(data, i * (class_num + 4) + 4, confidenceInfo, 0, class_num);
  93. float score = confidenceInfo.Max(); // 获取最大值
  94. int maxIndex = Array.IndexOf(confidenceInfo, score); // 获取最大值的位置
  95. int _centerX = (int)(rectData[0] * ratio_width);
  96. int _centerY = (int)(rectData[1] * ratio_height);
  97. int _width = (int)(rectData[2] * ratio_width);
  98. int _height = (int)(rectData[3] * ratio_height);
  99. detResults.Add(new DetectionResult(
  100. maxIndex,
  101. class_names[maxIndex],
  102. new Rect(_centerX - _width / 2, _centerY - _height / 2, _width, _height),
  103. score));
  104. }
  105. //NMS
  106. CvDnn.NMSBoxes(detResults.Select(x => x.Rect), detResults.Select(x => x.Confidence), conf_threshold, nms_threshold, out int[] indices);
  107. detResults = detResults.Where((x, index) => indices.Contains(index)).ToList();
  108. detectionResults = detResults;
  109. }
  110. internal List<DetectionResult> Detect(Mat image)
  111. {
  112. var t1 = Cv2.GetTickCount();
  113. Stopwatch stopwatch = new Stopwatch();
  114. stopwatch.Start();
  115. Preprocess(image);
  116. preprocessTime = stopwatch.Elapsed.TotalMilliseconds;
  117. stopwatch.Restart();
  118. using (Tensor input_x = Tensor.FromArray(input_tensor_data, new Shape(1,3, 640, 640)))
  119. {
  120. ir.Inputs[0] = input_x;
  121. }
  122. ir.Run();
  123. inferTime = stopwatch.Elapsed.TotalMilliseconds;
  124. stopwatch.Restart();
  125. outputData = ir.Outputs[0].GetData<float>().ToArray();
  126. Postprocess(outputData);
  127. postprocessTime = stopwatch.Elapsed.TotalMilliseconds;
  128. stopwatch.Stop();
  129. totalTime = preprocessTime + inferTime + postprocessTime;
  130. detFps = (double)stopwatch.Elapsed.TotalSeconds / (double)stopwatch.Elapsed.Ticks;
  131. var t2 = Cv2.GetTickCount();
  132. detFps = 1 / ((t2 - t1) / Cv2.GetTickFrequency());
  133. return detectionResults;
  134. }
  135. }
  136. }

ByteTracker.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ByteTrack
  7. {
  8. public class ByteTracker
  9. {
  10. readonly float _trackThresh;
  11. readonly float _highThresh;
  12. readonly float _matchThresh;
  13. readonly int _maxTimeLost;
  14. int _frameId = 0;
  15. int _trackIdCount = 0;
  16. readonly List<Track> _trackedTracks = new List<Track>(100);
  17. readonly List<Track> _lostTracks = new List<Track>(100);
  18. List<Track> _removedTracks = new List<Track>(100);
  19. public ByteTracker(int frameRate = 30, int trackBuffer = 30, float trackThresh = 0.5f, float highThresh = 0.6f, float matchThresh = 0.8f)
  20. {
  21. _trackThresh = trackThresh;
  22. _highThresh = highThresh;
  23. _matchThresh = matchThresh;
  24. _maxTimeLost = (int)(frameRate / 30.0 * trackBuffer);
  25. }
  26. /// <summary>
  27. ///
  28. /// </summary>
  29. /// <param name="objects"></param>
  30. /// <returns></returns>
  31. public IList<Track> Update(List<Track> tracks)
  32. {
  33. #region Step 1: Get detections
  34. _frameId++;
  35. // Create new Tracks using the result of object detection
  36. List<Track> detTracks = new List<Track>();
  37. List<Track> detLowTracks = new List<Track>();
  38. foreach (var obj in tracks)
  39. {
  40. if (obj.Score >= _trackThresh)
  41. {
  42. detTracks.Add(obj);
  43. }
  44. else
  45. {
  46. detLowTracks.Add(obj);
  47. }
  48. }
  49. // Create lists of existing STrack
  50. List<Track> activeTracks = new List<Track>();
  51. List<Track> nonActiveTracks = new List<Track>();
  52. foreach (var trackedTrack in _trackedTracks)
  53. {
  54. if (!trackedTrack.IsActivated)
  55. {
  56. nonActiveTracks.Add(trackedTrack);
  57. }
  58. else
  59. {
  60. activeTracks.Add(trackedTrack);
  61. }
  62. }
  63. var trackPool = activeTracks.Union(_lostTracks).ToArray();
  64. // Predict current pose by KF
  65. foreach (var track in trackPool)
  66. {
  67. track.Predict();
  68. }
  69. #endregion
  70. #region Step 2: First association, with IoU
  71. List<Track> currentTrackedTracks = new List<Track>();
  72. Track[] remainTrackedTracks;
  73. Track[] remainDetTracks;
  74. List<Track> refindTracks = new List<Track>();
  75. {
  76. var dists = CalcIouDistance(trackPool, detTracks);
  77. LinearAssignment(dists, trackPool.Length, detTracks.Count, _matchThresh,
  78. out var matchesIdx,
  79. out var unmatchTrackIdx,
  80. out var unmatchDetectionIdx);
  81. foreach (var matchIdx in matchesIdx)
  82. {
  83. var track = trackPool[matchIdx[0]];
  84. var det = detTracks[matchIdx[1]];
  85. if (track.State == TrackState.Tracked)
  86. {
  87. track.Update(det, _frameId);
  88. currentTrackedTracks.Add(track);
  89. }
  90. else
  91. {
  92. track.ReActivate(det, _frameId);
  93. refindTracks.Add(track);
  94. }
  95. }
  96. remainDetTracks = unmatchDetectionIdx.Select(unmatchIdx => detTracks[unmatchIdx]).ToArray();
  97. remainTrackedTracks = unmatchTrackIdx
  98. .Where(unmatchIdx => trackPool[unmatchIdx].State == TrackState.Tracked)
  99. .Select(unmatchIdx => trackPool[unmatchIdx])
  100. .ToArray();
  101. }
  102. #endregion
  103. #region Step 3: Second association, using low score dets
  104. List<Track> currentLostTracks = new List<Track>();
  105. {
  106. var dists = CalcIouDistance(remainTrackedTracks, detLowTracks);
  107. LinearAssignment(dists, remainTrackedTracks.Length, detLowTracks.Count, 0.5f,
  108. out var matchesIdx,
  109. out var unmatchTrackIdx,
  110. out var unmatchDetectionIdx);
  111. foreach (var matchIdx in matchesIdx)
  112. {
  113. var track = remainTrackedTracks[matchIdx[0]];
  114. var det = detLowTracks[matchIdx[1]];
  115. if (track.State == TrackState.Tracked)
  116. {
  117. track.Update(det, _frameId);
  118. currentTrackedTracks.Add(track);
  119. }
  120. else
  121. {
  122. track.ReActivate(det, _frameId);
  123. refindTracks.Add(track);
  124. }
  125. }
  126. foreach (var unmatchTrack in unmatchTrackIdx)
  127. {
  128. var track = remainTrackedTracks[unmatchTrack];
  129. if (track.State != TrackState.Lost)
  130. {
  131. track.MarkAsLost();
  132. currentLostTracks.Add(track);
  133. }
  134. }
  135. }
  136. #endregion
  137. #region Step 4: Init new tracks
  138. List<Track> currentRemovedTracks = new List<Track>();
  139. {
  140. // Deal with unconfirmed tracks, usually tracks with only one beginning frame
  141. var dists = CalcIouDistance(nonActiveTracks, remainDetTracks);
  142. LinearAssignment(dists, nonActiveTracks.Count, remainDetTracks.Length, 0.7f,
  143. out var matchesIdx,
  144. out var unmatchUnconfirmedIdx,
  145. out var unmatchDetectionIdx);
  146. foreach (var matchIdx in matchesIdx)
  147. {
  148. nonActiveTracks[matchIdx[0]].Update(remainDetTracks[matchIdx[1]], _frameId);
  149. currentTrackedTracks.Add(nonActiveTracks[matchIdx[0]]);
  150. }
  151. foreach (var unmatchIdx in unmatchUnconfirmedIdx)
  152. {
  153. var track = nonActiveTracks[unmatchIdx];
  154. track.MarkAsRemoved();
  155. currentRemovedTracks.Add(track);
  156. }
  157. // Add new stracks
  158. foreach (var unmatchIdx in unmatchDetectionIdx)
  159. {
  160. var track = remainDetTracks[unmatchIdx];
  161. if (track.Score < _highThresh)
  162. continue;
  163. _trackIdCount++;
  164. track.Activate(_frameId, _trackIdCount);
  165. currentTrackedTracks.Add(track);
  166. }
  167. }
  168. #endregion
  169. #region Step 5: Update state
  170. foreach (var lostTrack in _lostTracks)
  171. {
  172. if (_frameId - lostTrack.FrameId > _maxTimeLost)
  173. {
  174. lostTrack.MarkAsRemoved();
  175. currentRemovedTracks.Add(lostTrack);
  176. }
  177. }
  178. var trackedTracks = currentTrackedTracks.Union(refindTracks).ToArray();
  179. var lostTracks = _lostTracks.Except(trackedTracks).Union(currentLostTracks).Except(_removedTracks).ToArray();
  180. _removedTracks = _removedTracks.Union(currentRemovedTracks).ToList();
  181. RemoveDuplicateStracks(trackedTracks, lostTracks);
  182. #endregion
  183. return _trackedTracks.Where(track => track.IsActivated).ToArray();
  184. }
  185. /// <summary>
  186. ///
  187. /// </summary>
  188. /// <param name="aTracks"></param>
  189. /// <param name="bTracks"></param>
  190. /// <param name="aResults"></param>
  191. /// <param name="bResults"></param>
  192. void RemoveDuplicateStracks(IList<Track> aTracks, IList<Track> bTracks)
  193. {
  194. _trackedTracks.Clear();
  195. _lostTracks.Clear();
  196. List<(int, int)> overlappingCombinations;
  197. var ious = CalcIouDistance(aTracks, bTracks);
  198. if (ious is null)
  199. overlappingCombinations = new List<(int, int)>();
  200. else
  201. {
  202. var rows = ious.GetLength(0);
  203. var cols = ious.GetLength(1);
  204. overlappingCombinations = new List<(int, int)>(rows * cols / 2);
  205. for (var i = 0; i < rows; i++)
  206. for (var j = 0; j < cols; j++)
  207. if (ious[i, j] < 0.15f)
  208. overlappingCombinations.Add((i, j));
  209. }
  210. var aOverlapping = aTracks.Select(x => false).ToArray();
  211. var bOverlapping = bTracks.Select(x => false).ToArray();
  212. foreach (var (aIdx, bIdx) in overlappingCombinations)
  213. {
  214. var timep = aTracks[aIdx].FrameId - aTracks[aIdx].StartFrameId;
  215. var timeq = bTracks[bIdx].FrameId - bTracks[bIdx].StartFrameId;
  216. if (timep > timeq)
  217. bOverlapping[bIdx] = true;
  218. else
  219. aOverlapping[aIdx] = true;
  220. }
  221. for (var ai = 0; ai < aTracks.Count; ai++)
  222. if (!aOverlapping[ai])
  223. _trackedTracks.Add(aTracks[ai]);
  224. for (var bi = 0; bi < bTracks.Count; bi++)
  225. if (!bOverlapping[bi])
  226. _lostTracks.Add(bTracks[bi]);
  227. }
  228. /// <summary>
  229. ///
  230. /// </summary>
  231. /// <param name="costMatrix"></param>
  232. /// <param name="costMatrixSize"></param>
  233. /// <param name="costMatrixSizeSize"></param>
  234. /// <param name="thresh"></param>
  235. /// <param name="matches"></param>
  236. /// <param name="aUnmatched"></param>
  237. /// <param name="bUnmatched"></param>
  238. void LinearAssignment(float[,] costMatrix, int costMatrixSize, int costMatrixSizeSize, float thresh, out IList<int[]> matches, out IList<int> aUnmatched, out IList<int> bUnmatched)
  239. {
  240. matches = new List<int[]>();
  241. if (costMatrix is null)
  242. {
  243. aUnmatched = Enumerable.Range(0, costMatrixSize).ToArray();
  244. bUnmatched = Enumerable.Range(0, costMatrixSizeSize).ToArray();
  245. return;
  246. }
  247. bUnmatched = new List<int>();
  248. aUnmatched = new List<int>();
  249. var (rowsol, colsol) = Lapjv.Exec(costMatrix, true, thresh);
  250. for (var i = 0; i < rowsol.Length; i++)
  251. {
  252. if (rowsol[i] >= 0)
  253. matches.Add(new int[] { i, rowsol[i] });
  254. else
  255. aUnmatched.Add(i);
  256. }
  257. for (var i = 0; i < colsol.Length; i++)
  258. if (colsol[i] < 0)
  259. bUnmatched.Add(i);
  260. }
  261. /// <summary>
  262. ///
  263. /// </summary>
  264. /// <param name="aRects"></param>
  265. /// <param name="bRects"></param>
  266. /// <returns></returns>
  267. static float[,] CalcIous(IList<RectBox> aRects, IList<RectBox> bRects)
  268. {
  269. if (aRects.Count * bRects.Count == 0) return null;
  270. var ious = new float[aRects.Count, bRects.Count];
  271. for (var bi = 0; bi < bRects.Count; bi++)
  272. for (var ai = 0; ai < aRects.Count; ai++)
  273. ious[ai, bi] = bRects[bi].CalcIoU(aRects[ai]);
  274. return ious;
  275. }
  276. /// <summary>
  277. ///
  278. /// </summary>
  279. /// <param name="aTtracks"></param>
  280. /// <param name="bTracks"></param>
  281. /// <returns></returns>
  282. static float[,] CalcIouDistance(IEnumerable<Track> aTtracks, IEnumerable<Track> bTracks)
  283. {
  284. var aRects = aTtracks.Select(x => x.RectBox).ToArray();
  285. var bRects = bTracks.Select(x => x.RectBox).ToArray();
  286. var ious = CalcIous(aRects, bRects);
  287. if (ious is null) return null;
  288. var rows = ious.GetLength(0);
  289. var cols = ious.GetLength(1);
  290. var matrix = new float[rows, cols];
  291. for (var i = 0; i < rows; i++)
  292. for (var j = 0; j < cols; j++)
  293. matrix[i, j] = 1 - ious[i, j];
  294. return matrix;
  295. }
  296. }
  297. }

下载

源码下载

参考 

https://github.com/devhxj/Yolo8-ByteTrack-CSharp

https://github.com/sdcb/sdcb-openvino-yolov8-det

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

/ 登录

评论记录:

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

分类栏目

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