C# yolov8 TensorRT +ByteTrack Demo

C# yolov8 TensorRT +ByteTrack  Demo

目录

效果

说明 

项目

代码

Form2.cs

YoloV8.cs

ByteTracker.cs

下载

参考 


效果

说明 

环境

NVIDIA GeForce RTX 4060 Laptop GPU

cuda12.1+cudnn 8.8.1+TensorRT-8.6.1.6

版本和我不一致的需要重新编译TensorRtExtern.dll,TensorRtExtern源码地址:TensorRT-CSharp-API/src/TensorRtExtern at TensorRtSharp2.0 · guojin-yan/TensorRT-CSharp-API · GitHub

Windows版 CUDA安装参考:Windows版 CUDA安装_win cuda安装-CSDN博客

项目

代码

Form2.cs

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

namespace yolov8_TensorRT_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;


        /// <summary>
        /// 单图推理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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<DetectionResult> 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;

        }

        /// <summary>
        /// 窗体加载,初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            image_path = "test/dog.jpg";
            pictureBox1.Image = new Bitmap(image_path);

            model_path = "model/yolov8n.engine";

            if (!File.Exists(model_path))
            {
                //有点耗时,需等待
                Nvinfer.OnnxToEngine("model/yolov8n.onnx", 20);
            }

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

        }

        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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;
        }

        /// <summary>
        /// 选择视频
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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);

        }

        /// <summary>
        /// 视频推理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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<DetectionResult> 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;
            }

            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> track = new List<Track>();
                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", 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();
            }

        }

    }

}

using ByteTrack;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using TensorRtSharp.Custom;namespace yolov8_TensorRT_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;/// <summary>/// 单图推理/// </summary>/// <param name="sender"></param>/// <param name="e"></param>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<DetectionResult> 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;}/// <summary>/// 窗体加载,初始化/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Form1_Load(object sender, EventArgs e){image_path = "test/dog.jpg";pictureBox1.Image = new Bitmap(image_path);model_path = "model/yolov8n.engine";if (!File.Exists(model_path)){//有点耗时,需等待Nvinfer.OnnxToEngine("model/yolov8n.onnx", 20);}yoloV8 = new YoloV8(model_path, "model/lable.txt");}/// <summary>/// 选择图片/// </summary>/// <param name="sender"></param>/// <param name="e"></param>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;}/// <summary>/// 选择视频/// </summary>/// <param name="sender"></param>/// <param name="e"></param>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);}/// <summary>/// 视频推理/// </summary>/// <param name="sender"></param>/// <param name="e"></param>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<DetectionResult> detResults;// 获取视频的fpsdouble 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;}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> track = new List<Track>();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", 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();}}}}

YoloV8.cs

using OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using TensorRtSharp.Custom;namespace yolov8_TensorRT_Demo
{public class YoloV8{float[] input_tensor_data;float[] outputData;List<DetectionResult> detectionResults;int input_height;int input_width;Nvinfer predictor;public string[] class_names;int class_num;int box_num;float conf_threshold;float nms_threshold;float ratio_height;float ratio_width;public double preprocessTime;public double inferTime;public double postprocessTime;public double totalTime;public double detFps;public String DetectTime(){StringBuilder stringBuilder = new StringBuilder();stringBuilder.AppendLine($"Preprocess: {preprocessTime:F2}ms");stringBuilder.AppendLine($"Infer: {inferTime:F2}ms");stringBuilder.AppendLine($"Postprocess: {postprocessTime:F2}ms");stringBuilder.AppendLine($"Total: {totalTime:F2}ms");return stringBuilder.ToString();}public YoloV8(string model_path, string classer_path){predictor = new Nvinfer(model_path);class_names = File.ReadAllLines(classer_path, Encoding.UTF8);class_num = class_names.Length;input_height = 640;input_width = 640;box_num = 8400;conf_threshold = 0.25f;nms_threshold = 0.5f;detectionResults = new List<DetectionResult>();}void Preprocess(Mat image){//图片缩放int height = image.Rows;int width = image.Cols;Mat temp_image = image.Clone();if (height > input_height || width > input_width){float scale = Math.Min((float)input_height / height, (float)input_width / width);OpenCvSharp.Size new_size = new OpenCvSharp.Size((int)(width * scale), (int)(height * scale));Cv2.Resize(image, temp_image, new_size);}ratio_height = (float)height / temp_image.Rows;ratio_width = (float)width / temp_image.Cols;Mat input_img = new Mat();Cv2.CopyMakeBorder(temp_image, input_img, 0, input_height - temp_image.Rows, 0, input_width - temp_image.Cols, BorderTypes.Constant, 0);//归一化input_img.ConvertTo(input_img, MatType.CV_32FC3, 1.0 / 255);input_tensor_data = Common.ExtractMat(input_img);input_img.Dispose();temp_image.Dispose();}void Postprocess(float[] outputData){detectionResults.Clear();float[] data = Common.Transpose(outputData, class_num + 4, box_num);float[] confidenceInfo = new float[class_num];float[] rectData = new float[4];List<DetectionResult> detResults = new List<DetectionResult>();for (int i = 0; i < box_num; i++){Array.Copy(data, i * (class_num + 4), rectData, 0, 4);Array.Copy(data, i * (class_num + 4) + 4, confidenceInfo, 0, class_num);float score = confidenceInfo.Max(); // 获取最大值int maxIndex = Array.IndexOf(confidenceInfo, score); // 获取最大值的位置int _centerX = (int)(rectData[0] * ratio_width);int _centerY = (int)(rectData[1] * ratio_height);int _width = (int)(rectData[2] * ratio_width);int _height = (int)(rectData[3] * ratio_height);detResults.Add(new DetectionResult(maxIndex,class_names[maxIndex],new Rect(_centerX - _width / 2, _centerY - _height / 2, _width, _height),score));}//NMSCvDnn.NMSBoxes(detResults.Select(x => x.Rect), detResults.Select(x => x.Confidence), conf_threshold, nms_threshold, out int[] indices);detResults = detResults.Where((x, index) => indices.Contains(index)).ToList();detectionResults = detResults;}internal List<DetectionResult> Detect(Mat image){var t1 = Cv2.GetTickCount();Stopwatch stopwatch = new Stopwatch();stopwatch.Start();Preprocess(image);preprocessTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Restart();predictor.LoadInferenceData("images", input_tensor_data);predictor.infer();inferTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Restart();outputData = predictor.GetInferenceResult("output0");Postprocess(outputData);postprocessTime = stopwatch.Elapsed.TotalMilliseconds;stopwatch.Stop();totalTime = preprocessTime + inferTime + postprocessTime;detFps = (double)stopwatch.Elapsed.TotalSeconds / (double)stopwatch.Elapsed.Ticks;var t2 = Cv2.GetTickCount();detFps = 1 / ((t2 - t1) / Cv2.GetTickFrequency());return detectionResults;}}
}

ByteTracker.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace ByteTrack
{public class ByteTracker{readonly float _trackThresh;readonly float _highThresh;readonly float _matchThresh;readonly int _maxTimeLost;int _frameId = 0;int _trackIdCount = 0;readonly List<Track> _trackedTracks = new List<Track>(100);readonly List<Track> _lostTracks = new List<Track>(100);List<Track> _removedTracks = new List<Track>(100);public ByteTracker(int frameRate = 30, int trackBuffer = 30, float trackThresh = 0.5f, float highThresh = 0.6f, float matchThresh = 0.8f){_trackThresh = trackThresh;_highThresh = highThresh;_matchThresh = matchThresh;_maxTimeLost = (int)(frameRate / 30.0 * trackBuffer);}/// <summary>/// /// </summary>/// <param name="objects"></param>/// <returns></returns>public IList<Track> Update(List<Track> tracks){#region Step 1: Get detections _frameId++;// Create new Tracks using the result of object detectionList<Track> detTracks = new List<Track>();List<Track> detLowTracks = new List<Track>();foreach (var obj in tracks){if (obj.Score >= _trackThresh){detTracks.Add(obj);}else{detLowTracks.Add(obj);}}// Create lists of existing STrackList<Track> activeTracks = new List<Track>();List<Track> nonActiveTracks = new List<Track>();foreach (var trackedTrack in _trackedTracks){if (!trackedTrack.IsActivated){nonActiveTracks.Add(trackedTrack);}else{activeTracks.Add(trackedTrack);}}var trackPool = activeTracks.Union(_lostTracks).ToArray();// Predict current pose by KFforeach (var track in trackPool){track.Predict();}#endregion#region Step 2: First association, with IoU List<Track> currentTrackedTracks = new List<Track>();Track[] remainTrackedTracks;Track[] remainDetTracks;List<Track> refindTracks = new List<Track>();{var dists = CalcIouDistance(trackPool, detTracks);LinearAssignment(dists, trackPool.Length, detTracks.Count, _matchThresh,out var matchesIdx,out var unmatchTrackIdx,out var unmatchDetectionIdx);foreach (var matchIdx in matchesIdx){var track = trackPool[matchIdx[0]];var det = detTracks[matchIdx[1]];if (track.State == TrackState.Tracked){track.Update(det, _frameId);currentTrackedTracks.Add(track);}else{track.ReActivate(det, _frameId);refindTracks.Add(track);}}remainDetTracks = unmatchDetectionIdx.Select(unmatchIdx => detTracks[unmatchIdx]).ToArray();remainTrackedTracks = unmatchTrackIdx.Where(unmatchIdx => trackPool[unmatchIdx].State == TrackState.Tracked).Select(unmatchIdx => trackPool[unmatchIdx]).ToArray();}#endregion#region Step 3: Second association, using low score dets List<Track> currentLostTracks = new List<Track>();{var dists = CalcIouDistance(remainTrackedTracks, detLowTracks);LinearAssignment(dists, remainTrackedTracks.Length, detLowTracks.Count, 0.5f,out var matchesIdx,out var unmatchTrackIdx,out var unmatchDetectionIdx);foreach (var matchIdx in matchesIdx){var track = remainTrackedTracks[matchIdx[0]];var det = detLowTracks[matchIdx[1]];if (track.State == TrackState.Tracked){track.Update(det, _frameId);currentTrackedTracks.Add(track);}else{track.ReActivate(det, _frameId);refindTracks.Add(track);}}foreach (var unmatchTrack in unmatchTrackIdx){var track = remainTrackedTracks[unmatchTrack];if (track.State != TrackState.Lost){track.MarkAsLost();currentLostTracks.Add(track);}}}#endregion#region Step 4: Init new tracks List<Track> currentRemovedTracks = new List<Track>();{// Deal with unconfirmed tracks, usually tracks with only one beginning framevar dists = CalcIouDistance(nonActiveTracks, remainDetTracks);LinearAssignment(dists, nonActiveTracks.Count, remainDetTracks.Length, 0.7f,out var matchesIdx,out var unmatchUnconfirmedIdx,out var unmatchDetectionIdx);foreach (var matchIdx in matchesIdx){nonActiveTracks[matchIdx[0]].Update(remainDetTracks[matchIdx[1]], _frameId);currentTrackedTracks.Add(nonActiveTracks[matchIdx[0]]);}foreach (var unmatchIdx in unmatchUnconfirmedIdx){var track = nonActiveTracks[unmatchIdx];track.MarkAsRemoved();currentRemovedTracks.Add(track);}// Add new stracksforeach (var unmatchIdx in unmatchDetectionIdx){var track = remainDetTracks[unmatchIdx];if (track.Score < _highThresh)continue;_trackIdCount++;track.Activate(_frameId, _trackIdCount);currentTrackedTracks.Add(track);}}#endregion#region Step 5: Update stateforeach (var lostTrack in _lostTracks){if (_frameId - lostTrack.FrameId > _maxTimeLost){lostTrack.MarkAsRemoved();currentRemovedTracks.Add(lostTrack);}}var trackedTracks = currentTrackedTracks.Union(refindTracks).ToArray();var lostTracks = _lostTracks.Except(trackedTracks).Union(currentLostTracks).Except(_removedTracks).ToArray();_removedTracks = _removedTracks.Union(currentRemovedTracks).ToList();RemoveDuplicateStracks(trackedTracks, lostTracks);#endregionreturn _trackedTracks.Where(track => track.IsActivated).ToArray();}/// <summary>/// /// </summary>/// <param name="aTracks"></param>/// <param name="bTracks"></param>/// <param name="aResults"></param>/// <param name="bResults"></param>void RemoveDuplicateStracks(IList<Track> aTracks, IList<Track> bTracks){_trackedTracks.Clear();_lostTracks.Clear();List<(int, int)> overlappingCombinations;var ious = CalcIouDistance(aTracks, bTracks);if (ious is null)overlappingCombinations = new List<(int, int)>();else{var rows = ious.GetLength(0);var cols = ious.GetLength(1);overlappingCombinations = new List<(int, int)>(rows * cols / 2);for (var i = 0; i < rows; i++)for (var j = 0; j < cols; j++)if (ious[i, j] < 0.15f)overlappingCombinations.Add((i, j));}var aOverlapping = aTracks.Select(x => false).ToArray();var bOverlapping = bTracks.Select(x => false).ToArray();foreach (var (aIdx, bIdx) in overlappingCombinations){var timep = aTracks[aIdx].FrameId - aTracks[aIdx].StartFrameId;var timeq = bTracks[bIdx].FrameId - bTracks[bIdx].StartFrameId;if (timep > timeq)bOverlapping[bIdx] = true;elseaOverlapping[aIdx] = true;}for (var ai = 0; ai < aTracks.Count; ai++)if (!aOverlapping[ai])_trackedTracks.Add(aTracks[ai]);for (var bi = 0; bi < bTracks.Count; bi++)if (!bOverlapping[bi])_lostTracks.Add(bTracks[bi]);}/// <summary>/// /// </summary>/// <param name="costMatrix"></param>/// <param name="costMatrixSize"></param>/// <param name="costMatrixSizeSize"></param>/// <param name="thresh"></param>/// <param name="matches"></param>/// <param name="aUnmatched"></param>/// <param name="bUnmatched"></param>void LinearAssignment(float[,] costMatrix, int costMatrixSize, int costMatrixSizeSize, float thresh, out IList<int[]> matches, out IList<int> aUnmatched, out IList<int> bUnmatched){matches = new List<int[]>();if (costMatrix is null){aUnmatched = Enumerable.Range(0, costMatrixSize).ToArray();bUnmatched = Enumerable.Range(0, costMatrixSizeSize).ToArray();return;}bUnmatched = new List<int>();aUnmatched = new List<int>();var (rowsol, colsol) = Lapjv.Exec(costMatrix, true, thresh);for (var i = 0; i < rowsol.Length; i++){if (rowsol[i] >= 0)matches.Add(new int[] { i, rowsol[i] });elseaUnmatched.Add(i);}for (var i = 0; i < colsol.Length; i++)if (colsol[i] < 0)bUnmatched.Add(i);}/// <summary>/// /// </summary>/// <param name="aRects"></param>/// <param name="bRects"></param>/// <returns></returns>static float[,] CalcIous(IList<RectBox> aRects, IList<RectBox> bRects){if (aRects.Count * bRects.Count == 0) return null;var ious = new float[aRects.Count, bRects.Count];for (var bi = 0; bi < bRects.Count; bi++)for (var ai = 0; ai < aRects.Count; ai++)ious[ai, bi] = bRects[bi].CalcIoU(aRects[ai]);return ious;}/// <summary>/// /// </summary>/// <param name="aTtracks"></param>/// <param name="bTracks"></param>/// <returns></returns>static float[,] CalcIouDistance(IEnumerable<Track> aTtracks, IEnumerable<Track> bTracks){var aRects = aTtracks.Select(x => x.RectBox).ToArray();var bRects = bTracks.Select(x => x.RectBox).ToArray();var ious = CalcIous(aRects, bRects);if (ious is null) return null;var rows = ious.GetLength(0);var cols = ious.GetLength(1);var matrix = new float[rows, cols];for (var i = 0; i < rows; i++)for (var j = 0; j < cols; j++)matrix[i, j] = 1 - ious[i, j];return matrix;}}
}

下载

源码下载

参考 

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

https://github.com/guojin-yan/TensorRT-CSharp-API

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/20250.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

微调医疗大模型,与通用大模型效果对比

下面是一份CT描述&#xff1a; “肝脏大小、形态未见明确异常。肝S2见一结节状低密度影&#xff0c;大小约13x11mm&#xff0c;增强扫描呈明显渐进性强化&#xff0c;延迟期呈等密度。余肝实质内未见异常密度影或强化灶。肝内大血管及其分支走行未见异常&#xff0c;肝门区层次…

ip地址告诉别人安全吗?ip地址告诉别人会有什么风险

IP地址告诉别人安全吗&#xff1f;在数字化时代&#xff0c;IP地址作为网络连接的关键标识符&#xff0c;承载着重要的安全意义。然而&#xff0c;很多人可能并不清楚&#xff0c;轻易地将自己的IP地址告诉他人可能带来一系列安全风险。那么&#xff0c;IP地址告诉别人会有什么…

文件夹损坏0字节:全面解析、恢复技巧与预防策略

在数字时代&#xff0c;数据的完整性和安全性至关重要。然而&#xff0c;我们时常会遭遇文件夹损坏并显示为0字节的棘手问题。这种情况一旦发生&#xff0c;用户可能会面临数据丢失的风险。本文将详细探讨文件夹损坏0字节的现象&#xff0c;分析其背后的原因&#xff0c;并提供…

Redis-重定向

实验环境&#xff08;3主3从的Redis-Cluster&#xff09; 一、Redis重定向基础篇 1、MOVED重定向 Redis Custer 中&#xff0c;客户端可以向集群中任意节点发送请求。此时当前节点先对 Key 进行 CRC 16 计算&#xff0c;然后按 16384 取模确定 Slot 槽。确定该 Slot 槽所对应的…

为什么使用短链系统?

短链接&#xff08;Short Link&#xff09;是指将一个原始的长 URL&#xff08;Uniform Resource Locator&#xff09;通过特定的算法或服务转化为一个更短、易于记忆的 URL。短链接通常只包含几个字符&#xff0c;而原始的长 URL 可能会非常长。 短链接的原理非常简单&#x…

【Java数据结构】详解LinkedList与链表(二)

目录 1.❤️❤️前言~&#x1f973;&#x1f389;&#x1f389;&#x1f389; 2.反转一个单链表 3. 找到链表的中间节点 4.输入一个链表&#xff0c;输出该链表中倒数第k个结点。 5.合并两个有序链表 6.链表分割 7. 判定链表的回文结构 8.输入两个链表&#xff0c;找…

打印机的ip不同且连不上

打印机的ip不同且连不上 1.问题分析2.修改网段3.验证网络 1.问题分析 主要是打印机的网段和电脑不在同一个网段 2.修改网段 3.验证网络

Web前端三大主流框:React、Vue 和 Angular

在当今快速发展的 Web 开发领域&#xff0c;选择合适的前端框架对于项目的成功至关重要。React、Vue 和 Angular 作为三大主流前端框架&#xff0c;凭借其强大的功能和灵活的特性&#xff0c;赢得了众多开发者的青睐。本文将对这三大框架进行解析&#xff0c;帮助开发者了解它们…

C/C++学习笔记 C读取文本文件

1、简述 要读取文本文件&#xff0c;需要按照以下步骤操作&#xff1a; 首先&#xff0c;使用该函数打开文本文件fopen()。其次&#xff0c;使用fgets()或fgetc()函数从文件中读取文本。第三&#xff0c;使用函数关闭文件fclose()。 2、每次从文件中读取一个字符 要从文本文…

整理一下win7系统java、python等各个可安装版本

最近使用win7系统&#xff0c;遇到了很多版本不兼容的问题&#xff0c;把我现在安装好的可使用的分享给大家 jdk 1.8 maven-3.9.6 centos 7 python 3.7.4 docker DockerToolbox-18.01.0-ce win10是直接一个docker软件&#xff0c;win7要安装这三个 datagrip-2020.2.3 d…

2.1Docker安装MySQL8.0

2.1 Docker安装MySQL8.0 1.拉取MySQL docker pull mysql:latest如&#xff1a;拉取MySQL8.0.33版本 docker pull mysql:8.0.332. 启动镜像 docker run -p 3307:3306 --name mysql8 -e MYSQL_ROOT_PASSWORDHgh75667% -d mysql:8.0.33-p 3307:3306 把mysql默认的3306端口映射…

CentOs-7.5 root密码忘记了,如何重置密码?

VWmare软件版本&#xff1a;VMware Workstation 16 Pro Centos系统版本&#xff1a;CentOS-7.5-x86 64-Minimal-1804 文章目录 问题描述如何解决&#xff1f; 问题描述 长时间没有使用Linux系统&#xff0c;root用户密码忘记了&#xff0c;登陆不上系统&#xff0c;如下图所示…

FreeRTOS基础(三):动态创建任务

上一篇博客&#xff0c;我们讲解了FreeRTOS中&#xff0c;我们讲解了创建任务和删除任务的API函数&#xff0c;那么这一讲&#xff0c;我们从实战出发&#xff0c;规范我们在FreeRTOS下的编码风格&#xff0c;掌握动态创建任务的编码风格&#xff0c;达到实战应用&#xff01; …

用贪心算法进行10进制整数转化为2进制数

十进制整数转二进制数用什么方法&#xff1f;网上一搜&#xff0c;大部分答案都是用短除法&#xff0c;也就是除2反向取余法。这种方法是最基本最常用的&#xff0c;但是计算步骤多&#xff0c;还容易出错&#xff0c;那么还有没有其他更好的方法吗&#xff1f; 一、短除反向取…

AdroitFisherman模块安装日志(2024/5/31)

安装指令 pip install AdroitFisherman-0.0.29.tar.gz -v 安装条件 1:Microsoft Visual Studio Build Tools 2:python 3.10.x 显示输出 Using pip 24.0 from C:\Users\12952\AppData\Local\Programs\Python\Python310\lib\site-packages\pip (python 3.10) Processing c:\u…

matlab GUI界面设计

【实验内容】 用MATLAB的GUI程序设计一个具备图像边缘检测功能的用户界面&#xff0c;该设计程序有以下基本功能&#xff1a; &#xff08;1&#xff09;图像的读取和保存。 &#xff08;2&#xff09;设计图形用户界面&#xff0c;让用户对图像进行彩色图像到灰度图像的转换…

2.1 OpenCV随手简记(二)

为后续项目学习做准备&#xff0c;我们需要了解LinuxOpenCV、Mediapipe、ROS、QT等知识。 一、图像显示与保存 1、基本原理 1.1 图像像素存储形式 首先得了解下图像在计算机中存储形式&#xff1a;(为了方便画图&#xff0c;每列像素值都写一样了)。对于只有黑白颜色的灰度…

[有监督学习]2.详细图解正则化

正则化 正则化是防止过拟合的一种方法&#xff0c;与线性回归等算法配合使用。通过向损失函数增加惩罚项的方式对模型施加制约&#xff0c;有望提高模型的泛化能力。 概述 正则化是防止过拟合的方法&#xff0c;用于机器学习模型的训练阶段。过拟合是模型在验证数据上产生的误…

Java文件IO

White graces&#xff1a;个人主页 &#x1f649;专栏推荐:Java入门知识&#x1f649; &#x1f649; 内容推荐:JUC常见类&#x1f649; &#x1f439;今日诗词:东风吹柳日初长&#xff0c;雨馀芳草斜阳&#x1f439; ⛳️点赞 ☀️收藏⭐️关注&#x1f4ac;卑微小博主&…

Three.js 研究:4、创建设备底部旋转的科技感圆环

1、实现效果 2、PNG转SVG 2.1、原始物料 使用网站工具https://convertio.co/zh/png-svg/进行PNG转SVG 3、导入SVG至Blender 4、制作旋转动画 4.1、给圆环着色 4.2、修改圆环中心位置 4.3、让圆环旋转起来 参考一下文章 Three.js 研究&#xff1a;1、如何让物体动起来 Thre…