首页 最新 热门 推荐

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

C# yolov8 TensorRT Demo

  • 25-02-19 03:20
  • 2477
  • 12297
blog.csdn.net

C# yolov8 TensorRT Demo

目录

效果

说明 

项目

代码

下载


效果

说明 

环境

NVIDIA GeForce RTX 4060 Laptop GPU

cuda12.1+cudnn 8.8.1+TensorRT-8.6.1.6

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

Windows版 CUDA安装参考:http://iyenn.com/rec/1661921.html

项目

代码

Form2.cs

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;


        ///


        /// 单图推理
        ///

        ///
        ///
        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/zidane.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");

        }

        ///


        /// 选择图片
        ///

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

            button3_Click(null, null);

        }

        ///


        /// 视频推理
        ///

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

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

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

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

        }
    }

}
 

  1. using OpenCvSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Threading;
  8. using System.Windows.Forms;
  9. using TensorRtSharp.Custom;
  10. namespace yolov8_TensorRT_Demo
  11. {
  12. public partial class Form2 : Form
  13. {
  14. public Form2()
  15. {
  16. InitializeComponent();
  17. }
  18. string imgFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
  19. YoloV8 yoloV8;
  20. Mat image;
  21. string image_path = "";
  22. string model_path;
  23. string video_path = "";
  24. string videoFilter = "*.mp4|*.mp4;";
  25. VideoCapture vcapture;
  26. VideoWriter vwriter;
  27. bool saveDetVideo = false;
  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/zidane.jpg";
  68. pictureBox1.Image = new Bitmap(image_path);
  69. model_path = "model/yolov8n.engine";
  70. if (!File.Exists(model_path))
  71. {
  72. //有点耗时,需等待
  73. Nvinfer.OnnxToEngine("model/yolov8n.onnx", 20);
  74. }
  75. yoloV8 = new YoloV8(model_path, "model/lable.txt");
  76. }
  77. /// <summary>
  78. /// 选择图片
  79. /// </summary>
  80. /// <param name="sender"></param>
  81. /// <param name="e"></param>
  82. private void button1_Click_1(object sender, EventArgs e)
  83. {
  84. OpenFileDialog ofd = new OpenFileDialog();
  85. ofd.Filter = imgFilter;
  86. if (ofd.ShowDialog() != DialogResult.OK) return;
  87. pictureBox1.Image = null;
  88. image_path = ofd.FileName;
  89. pictureBox1.Image = new Bitmap(image_path);
  90. textBox1.Text = "";
  91. pictureBox2.Image = null;
  92. }
  93. /// <summary>
  94. /// 选择视频
  95. /// </summary>
  96. /// <param name="sender"></param>
  97. /// <param name="e"></param>
  98. private void button4_Click(object sender, EventArgs e)
  99. {
  100. OpenFileDialog ofd = new OpenFileDialog();
  101. ofd.Filter = videoFilter;
  102. ofd.InitialDirectory = Application.StartupPath + "\\test";
  103. if (ofd.ShowDialog() != DialogResult.OK) return;
  104. video_path = ofd.FileName;
  105. button3_Click(null, null);
  106. }
  107. /// <summary>
  108. /// 视频推理
  109. /// </summary>
  110. /// <param name="sender"></param>
  111. /// <param name="e"></param>
  112. private void button3_Click(object sender, EventArgs e)
  113. {
  114. if (video_path == null)
  115. {
  116. return;
  117. }
  118. textBox1.Text = "开始检测";
  119. Application.DoEvents();
  120. Thread thread = new Thread(new ThreadStart(VideoDetection));
  121. thread.Start();
  122. thread.Join();
  123. textBox1.Text = "检测完成!";
  124. }
  125. void VideoDetection()
  126. {
  127. vcapture = new VideoCapture(video_path);
  128. if (!vcapture.IsOpened())
  129. {
  130. MessageBox.Show("打开视频文件失败");
  131. return;
  132. }
  133. Mat frame = new Mat();
  134. List<DetectionResult> detResults;
  135. // 获取视频的fps
  136. double videoFps = vcapture.Get(VideoCaptureProperties.Fps);
  137. // 计算等待时间(毫秒)
  138. int delay = (int)(1000 / videoFps);
  139. Stopwatch _stopwatch = new Stopwatch();
  140. if (checkBox1.Checked)
  141. {
  142. vwriter = new VideoWriter("out.mp4", FourCC.X264, vcapture.Fps, new OpenCvSharp.Size(vcapture.FrameWidth, vcapture.FrameHeight));
  143. saveDetVideo = true;
  144. }
  145. else {
  146. saveDetVideo = false;
  147. }
  148. while (vcapture.Read(frame))
  149. {
  150. if (frame.Empty())
  151. {
  152. MessageBox.Show("读取失败");
  153. return;
  154. }
  155. _stopwatch.Restart();
  156. delay = (int)(1000 / videoFps);
  157. detResults = yoloV8.Detect(frame);
  158. //绘制结果
  159. foreach (DetectionResult r in detResults)
  160. {
  161. 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);
  162. Cv2.Rectangle(frame, r.Rect, Scalar.Red, thickness: 2);
  163. }
  164. Cv2.PutText(frame, "preprocessTime:" + yoloV8.preprocessTime.ToString("F2")+"ms", new OpenCvSharp.Point(10, 30), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  165. Cv2.PutText(frame, "inferTime:" + yoloV8.inferTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 70), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  166. Cv2.PutText(frame, "postprocessTime:" + yoloV8.postprocessTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 110), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  167. Cv2.PutText(frame, "totalTime:" + yoloV8.totalTime.ToString("F2") + "ms", new OpenCvSharp.Point(10, 150), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  168. Cv2.PutText(frame, "video fps:" + videoFps.ToString("F2"), new OpenCvSharp.Point(10, 190), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  169. Cv2.PutText(frame, "det fps:" + yoloV8.detFps.ToString("F2"), new OpenCvSharp.Point(10, 230), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
  170. if (saveDetVideo)
  171. {
  172. vwriter.Write(frame);
  173. }
  174. Cv2.ImShow("DetectionResult", frame);
  175. // for test
  176. // delay = 1;
  177. delay = (int)(delay - _stopwatch.ElapsedMilliseconds);
  178. if (delay <= 0)
  179. {
  180. delay = 1;
  181. }
  182. //Console.WriteLine("delay:" + delay.ToString()) ;
  183. if (Cv2.WaitKey(delay) == 27)
  184. {
  185. break; // 如果按下ESC,退出循环
  186. }
  187. }
  188. Cv2.DestroyAllWindows();
  189. vcapture.Release();
  190. if (saveDetVideo)
  191. {
  192. vwriter.Release();
  193. }
  194. }
  195. }
  196. }

YoloV8.cs

  1. using OpenCvSharp;
  2. using OpenCvSharp.Dnn;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using TensorRtSharp.Custom;
  10. namespace yolov8_TensorRT_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. Nvinfer predictor;
  20. 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. predictor = new Nvinfer(model_path);
  44. class_names = File.ReadAllLines(classer_path, Encoding.UTF8);
  45. class_num = class_names.Length;
  46. input_height = 640;
  47. input_width = 640;
  48. box_num = 8400;
  49. conf_threshold = 0.25f;
  50. nms_threshold = 0.5f;
  51. detectionResults = new List<DetectionResult>();
  52. }
  53. void Preprocess(Mat image)
  54. {
  55. //图片缩放
  56. int height = image.Rows;
  57. int width = image.Cols;
  58. Mat temp_image = image.Clone();
  59. if (height > input_height || width > input_width)
  60. {
  61. float scale = Math.Min((float)input_height / height, (float)input_width / width);
  62. OpenCvSharp.Size new_size = new OpenCvSharp.Size((int)(width * scale), (int)(height * scale));
  63. Cv2.Resize(image, temp_image, new_size);
  64. }
  65. ratio_height = (float)height / temp_image.Rows;
  66. ratio_width = (float)width / temp_image.Cols;
  67. Mat input_img = new Mat();
  68. Cv2.CopyMakeBorder(temp_image, input_img, 0, input_height - temp_image.Rows, 0, input_width - temp_image.Cols, BorderTypes.Constant, 0);
  69. //归一化
  70. input_img.ConvertTo(input_img, MatType.CV_32FC3, 1.0 / 255);
  71. input_tensor_data = Common.ExtractMat(input_img);
  72. input_img.Dispose();
  73. temp_image.Dispose();
  74. }
  75. void Postprocess(float[] outputData)
  76. {
  77. detectionResults.Clear();
  78. float[] data = Common.Transpose(outputData, class_num + 4, box_num);
  79. float[] confidenceInfo = new float[class_num];
  80. float[] rectData = new float[4];
  81. List<DetectionResult> detResults = new List<DetectionResult>();
  82. for (int i = 0; i < box_num; i++)
  83. {
  84. Array.Copy(data, i * (class_num + 4), rectData, 0, 4);
  85. Array.Copy(data, i * (class_num + 4) + 4, confidenceInfo, 0, class_num);
  86. float score = confidenceInfo.Max(); // 获取最大值
  87. int maxIndex = Array.IndexOf(confidenceInfo, score); // 获取最大值的位置
  88. int _centerX = (int)(rectData[0] * ratio_width);
  89. int _centerY = (int)(rectData[1] * ratio_height);
  90. int _width = (int)(rectData[2] * ratio_width);
  91. int _height = (int)(rectData[3] * ratio_height);
  92. detResults.Add(new DetectionResult(
  93. maxIndex,
  94. class_names[maxIndex],
  95. new Rect(_centerX - _width / 2, _centerY - _height / 2, _width, _height),
  96. score));
  97. }
  98. //NMS
  99. CvDnn.NMSBoxes(detResults.Select(x => x.Rect), detResults.Select(x => x.Confidence), conf_threshold, nms_threshold, out int[] indices);
  100. detResults = detResults.Where((x, index) => indices.Contains(index)).ToList();
  101. detectionResults = detResults;
  102. }
  103. internal List<DetectionResult> Detect(Mat image)
  104. {
  105. var t1 = Cv2.GetTickCount();
  106. Stopwatch stopwatch = new Stopwatch();
  107. stopwatch.Start();
  108. Preprocess(image);
  109. preprocessTime = stopwatch.Elapsed.TotalMilliseconds;
  110. stopwatch.Restart();
  111. predictor.LoadInferenceData("images", input_tensor_data);
  112. predictor.infer();
  113. inferTime = stopwatch.Elapsed.TotalMilliseconds;
  114. stopwatch.Restart();
  115. outputData = predictor.GetInferenceResult("output0");
  116. Postprocess(outputData);
  117. postprocessTime = stopwatch.Elapsed.TotalMilliseconds;
  118. stopwatch.Stop();
  119. totalTime = preprocessTime + inferTime + postprocessTime;
  120. detFps = (double)stopwatch.Elapsed.TotalSeconds / (double)stopwatch.Elapsed.Ticks;
  121. var t2 = Cv2.GetTickCount();
  122. detFps = 1 / ((t2 - t1) / Cv2.GetTickFrequency());
  123. return detectionResults;
  124. }
  125. }
  126. }

下载

源码下载

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

/ 登录

评论记录:

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

分类栏目

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