首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐
2025年7月13日 星期日 5:53am

C# OpenCvSharp DNN 部署yoloX

  • 25-02-19 03:00
  • 4285
  • 10099
blog.csdn.net

目录

效果

模型信息

项目

代码

下载


C# OpenCvSharp DNN 部署yoloX

效果

模型信息

Inputs
-------------------------
name:images
tensor:Float[1, 3, 640, 640]
---------------------------------------------------------------

Outputs
-------------------------
name:output
tensor:Float[1, 8400, 85]
---------------------------------------------------------------

项目

代码

using OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace OpenCvSharp_DNN_Demo
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string image_path = "";

        DateTime dt1 = DateTime.Now;
        DateTime dt2 = DateTime.Now;

        float prob_threshold;
        float nms_threshold;

        float[] stride = new float[3] { 8.0f, 16.0f, 32.0f };

        int[] input_shape = new int[] { 640, 640 };   // height, width

        float[] mean = new float[3] { 0.485f, 0.456f, 0.406f };
        float[] std = new float[3] { 0.229f, 0.224f, 0.225f };
        float scale = 1.0f;

        string modelpath;

        int inpHeight;
        int inpWidth;

        List class_names;
        int num_class;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        public Mat Normalize(Mat src)
        {
            Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);
            Mat[] bgr = src.Split();
            for (int i = 0; i < bgr.Length; ++i)
            {
                bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1.0 / (255.0 * std[i]), (0.0 - mean[i]) / std[i]);
            }
            Cv2.Merge(bgr, src);
            foreach (Mat channel in bgr)
            {
                channel.Dispose();
            }
            return src;
        }

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

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

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

        private void Form1_Load(object sender, EventArgs e)
        {
            prob_threshold = 0.6f;
            nms_threshold = 0.6f;

            modelpath = "model/yolox_s.onnx";

            inpHeight = 640;
            inpWidth = 640;

            opencv_net = CvDnn.ReadNetFromOnnx(modelpath);

            class_names = new List();
            StreamReader sr = new StreamReader("model/coco.names");
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                class_names.Add(line);
            }
            num_class = class_names.Count();

            image_path = "test_img/dog.jpg";
            pictureBox1.Image = new Bitmap(image_path);

        }

        Mat ResizeImage(Mat srcimg)
        {

            float r = (float)Math.Min(input_shape[1] / (srcimg.Cols * 1.0), input_shape[0] / (srcimg.Rows * 1.0));
            scale = r;
            int unpad_w = (int)(r * srcimg.Cols);
            int unpad_h = (int)(r * srcimg.Rows);
            Mat re = new Mat(unpad_h, unpad_w, MatType.CV_8UC3);
            Cv2.Resize(srcimg, re, new OpenCvSharp.Size(unpad_w, unpad_h));
            Mat outMat = new Mat(input_shape[1], input_shape[0], MatType.CV_8UC3, new Scalar(114, 114, 114));
            re.CopyTo(new Mat(outMat, new Rect(0, 0, re.Cols, re.Rows)));
            return outMat;
        }


        private unsafe void button2_Click(object sender, EventArgs e)
        {
            if (image_path == "")
            {
                return;
            }
            textBox1.Text = "检测中,请稍等……";
            pictureBox2.Image = null;
            Application.DoEvents();

            image = new Mat(image_path);

            Mat dstimg = ResizeImage(image);

            dstimg = Normalize(dstimg);

            BN_image = CvDnn.BlobFromImage(dstimg);

            //配置图片输入数据
            opencv_net.SetInput(BN_image);

            //模型推理,读取推理结果
            Mat[] outs = new Mat[] { new Mat() };
            string[] outBlobNames = opencv_net.GetUnconnectedOutLayersNames().ToArray();

            dt1 = DateTime.Now;

            opencv_net.Forward(outs, outBlobNames);

            dt2 = DateTime.Now;

            int num_proposal = outs[0].Size(1);
            outs[0] = outs[0].Reshape(0, num_proposal);

            float* pdata = (float*)outs[0].Data;

            int row_ind = 0;
            int nout = num_class + 5;

            List boxes = new List();
            List confidences = new List();
            List classIds = new List();

            for (int n = 0; n < 3; n++)
            {
                int num_grid_x = (int)(inpWidth / stride[n]);
                int num_grid_y = (int)(inpHeight / stride[n]);

                for (int i = 0; i < num_grid_y; i++)
                {
                    for (int j = 0; j < num_grid_x; j++)
                    {
                        float box_score = pdata[4];
                        Mat scores = outs[0].Row(row_ind).ColRange(5, outs[0].Cols);

                        double minVal, max_class_socre;
                        OpenCvSharp.Point minLoc, classIdPoint;
                        // Get the value and location of the maximum score
                        Cv2.MinMaxLoc(scores, out minVal, out max_class_socre, out minLoc, out classIdPoint);

                        int class_idx = classIdPoint.X;

                        float cls_score = pdata[5 + class_idx];
                        float box_prob = box_score * cls_score;
                        if (box_prob > prob_threshold)
                        {
                            float x_center = (pdata[0] + j) * stride[n];
                            float y_center = (pdata[1] + i) * stride[n];
                            float w = (float)(Math.Exp(pdata[2]) * stride[n]);
                            float h = (float)(Math.Exp(pdata[3]) * stride[n]);
                            float x0 = x_center - w * 0.5f;
                            float y0 = y_center - h * 0.5f;

                            classIds.Add(class_idx);
                            confidences.Add(box_prob);
                            boxes.Add(new Rect((int)x0, (int)y0, (int)w, (int)h));
                        }

                        pdata += nout;
                        row_ind++;
                    }
                }
            }

            int[] indices;
            CvDnn.NMSBoxes(boxes, confidences, prob_threshold, nms_threshold, out indices);

            result_image = image.Clone();

            for (int ii = 0; ii < indices.Length; ++ii)
            {
                int idx = indices[ii];
                Rect box = boxes[idx];

                // adjust offset to original unpadded
                float x0 = box.X / scale; ;
                float y0 = box.Y / scale; ;
                float x1 = (box.X + box.Width) / scale;
                float y1 = (box.Y + box.Height) / scale;

                // clip
                x0 = Math.Max(Math.Min(x0, (float)(image.Cols - 1)), 0.0f);
                y0 = Math.Max(Math.Min(y0, (float)(image.Rows - 1)), 0.0f);
                x1 = Math.Max(Math.Min(x1, (float)(image.Cols - 1)), 0.0f);
                y1 = Math.Max(Math.Min(y1, (float)(image.Rows - 1)), 0.0f);

                Cv2.Rectangle(result_image, new OpenCvSharp.Point(x0, y0), new OpenCvSharp.Point(x1, y1), new Scalar(0, 255, 0), 2);
                string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
                Cv2.PutText(result_image, label, new OpenCvSharp.Point(x0, y0 - 5), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2);
            }

            pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
            textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";

        }

        private void pictureBox2_DoubleClick(object sender, EventArgs e)
        {
            Common.ShowNormalImg(pictureBox2.Image);
        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            Common.ShowNormalImg(pictureBox1.Image);
        }
    }
}

  1. using OpenCvSharp;
  2. using OpenCvSharp.Dnn;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Windows.Forms;
  9. namespace OpenCvSharp_DNN_Demo
  10. {
  11. public partial class frmMain : Form
  12. {
  13. public frmMain()
  14. {
  15. InitializeComponent();
  16. }
  17. string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
  18. string image_path = "";
  19. DateTime dt1 = DateTime.Now;
  20. DateTime dt2 = DateTime.Now;
  21. float prob_threshold;
  22. float nms_threshold;
  23. float[] stride = new float[3] { 8.0f, 16.0f, 32.0f };
  24. int[] input_shape = new int[] { 640, 640 }; // height, width
  25. float[] mean = new float[3] { 0.485f, 0.456f, 0.406f };
  26. float[] std = new float[3] { 0.229f, 0.224f, 0.225f };
  27. float scale = 1.0f;
  28. string modelpath;
  29. int inpHeight;
  30. int inpWidth;
  31. List<string> class_names;
  32. int num_class;
  33. Net opencv_net;
  34. Mat BN_image;
  35. Mat image;
  36. Mat result_image;
  37. public Mat Normalize(Mat src)
  38. {
  39. Cv2.CvtColor(src, src, ColorConversionCodes.BGR2RGB);
  40. Mat[] bgr = src.Split();
  41. for (int i = 0; i < bgr.Length; ++i)
  42. {
  43. bgr[i].ConvertTo(bgr[i], MatType.CV_32FC1, 1.0 / (255.0 * std[i]), (0.0 - mean[i]) / std[i]);
  44. }
  45. Cv2.Merge(bgr, src);
  46. foreach (Mat channel in bgr)
  47. {
  48. channel.Dispose();
  49. }
  50. return src;
  51. }
  52. private void button1_Click(object sender, EventArgs e)
  53. {
  54. OpenFileDialog ofd = new OpenFileDialog();
  55. ofd.Filter = fileFilter;
  56. if (ofd.ShowDialog() != DialogResult.OK) return;
  57. pictureBox1.Image = null;
  58. pictureBox2.Image = null;
  59. textBox1.Text = "";
  60. image_path = ofd.FileName;
  61. pictureBox1.Image = new Bitmap(image_path);
  62. image = new Mat(image_path);
  63. }
  64. private void Form1_Load(object sender, EventArgs e)
  65. {
  66. prob_threshold = 0.6f;
  67. nms_threshold = 0.6f;
  68. modelpath = "model/yolox_s.onnx";
  69. inpHeight = 640;
  70. inpWidth = 640;
  71. opencv_net = CvDnn.ReadNetFromOnnx(modelpath);
  72. class_names = new List<string>();
  73. StreamReader sr = new StreamReader("model/coco.names");
  74. string line;
  75. while ((line = sr.ReadLine()) != null)
  76. {
  77. class_names.Add(line);
  78. }
  79. num_class = class_names.Count();
  80. image_path = "test_img/dog.jpg";
  81. pictureBox1.Image = new Bitmap(image_path);
  82. }
  83. Mat ResizeImage(Mat srcimg)
  84. {
  85. float r = (float)Math.Min(input_shape[1] / (srcimg.Cols * 1.0), input_shape[0] / (srcimg.Rows * 1.0));
  86. scale = r;
  87. int unpad_w = (int)(r * srcimg.Cols);
  88. int unpad_h = (int)(r * srcimg.Rows);
  89. Mat re = new Mat(unpad_h, unpad_w, MatType.CV_8UC3);
  90. Cv2.Resize(srcimg, re, new OpenCvSharp.Size(unpad_w, unpad_h));
  91. Mat outMat = new Mat(input_shape[1], input_shape[0], MatType.CV_8UC3, new Scalar(114, 114, 114));
  92. re.CopyTo(new Mat(outMat, new Rect(0, 0, re.Cols, re.Rows)));
  93. return outMat;
  94. }
  95. private unsafe void button2_Click(object sender, EventArgs e)
  96. {
  97. if (image_path == "")
  98. {
  99. return;
  100. }
  101. textBox1.Text = "检测中,请稍等……";
  102. pictureBox2.Image = null;
  103. Application.DoEvents();
  104. image = new Mat(image_path);
  105. Mat dstimg = ResizeImage(image);
  106. dstimg = Normalize(dstimg);
  107. BN_image = CvDnn.BlobFromImage(dstimg);
  108. //配置图片输入数据
  109. opencv_net.SetInput(BN_image);
  110. //模型推理,读取推理结果
  111. Mat[] outs = new Mat[] { new Mat() };
  112. string[] outBlobNames = opencv_net.GetUnconnectedOutLayersNames().ToArray();
  113. dt1 = DateTime.Now;
  114. opencv_net.Forward(outs, outBlobNames);
  115. dt2 = DateTime.Now;
  116. int num_proposal = outs[0].Size(1);
  117. outs[0] = outs[0].Reshape(0, num_proposal);
  118. float* pdata = (float*)outs[0].Data;
  119. int row_ind = 0;
  120. int nout = num_class + 5;
  121. List<Rect> boxes = new List<Rect>();
  122. List<float> confidences = new List<float>();
  123. List<int> classIds = new List<int>();
  124. for (int n = 0; n < 3; n++)
  125. {
  126. int num_grid_x = (int)(inpWidth / stride[n]);
  127. int num_grid_y = (int)(inpHeight / stride[n]);
  128. for (int i = 0; i < num_grid_y; i++)
  129. {
  130. for (int j = 0; j < num_grid_x; j++)
  131. {
  132. float box_score = pdata[4];
  133. Mat scores = outs[0].Row(row_ind).ColRange(5, outs[0].Cols);
  134. double minVal, max_class_socre;
  135. OpenCvSharp.Point minLoc, classIdPoint;
  136. // Get the value and location of the maximum score
  137. Cv2.MinMaxLoc(scores, out minVal, out max_class_socre, out minLoc, out classIdPoint);
  138. int class_idx = classIdPoint.X;
  139. float cls_score = pdata[5 + class_idx];
  140. float box_prob = box_score * cls_score;
  141. if (box_prob > prob_threshold)
  142. {
  143. float x_center = (pdata[0] + j) * stride[n];
  144. float y_center = (pdata[1] + i) * stride[n];
  145. float w = (float)(Math.Exp(pdata[2]) * stride[n]);
  146. float h = (float)(Math.Exp(pdata[3]) * stride[n]);
  147. float x0 = x_center - w * 0.5f;
  148. float y0 = y_center - h * 0.5f;
  149. classIds.Add(class_idx);
  150. confidences.Add(box_prob);
  151. boxes.Add(new Rect((int)x0, (int)y0, (int)w, (int)h));
  152. }
  153. pdata += nout;
  154. row_ind++;
  155. }
  156. }
  157. }
  158. int[] indices;
  159. CvDnn.NMSBoxes(boxes, confidences, prob_threshold, nms_threshold, out indices);
  160. result_image = image.Clone();
  161. for (int ii = 0; ii < indices.Length; ++ii)
  162. {
  163. int idx = indices[ii];
  164. Rect box = boxes[idx];
  165. // adjust offset to original unpadded
  166. float x0 = box.X / scale; ;
  167. float y0 = box.Y / scale; ;
  168. float x1 = (box.X + box.Width) / scale;
  169. float y1 = (box.Y + box.Height) / scale;
  170. // clip
  171. x0 = Math.Max(Math.Min(x0, (float)(image.Cols - 1)), 0.0f);
  172. y0 = Math.Max(Math.Min(y0, (float)(image.Rows - 1)), 0.0f);
  173. x1 = Math.Max(Math.Min(x1, (float)(image.Cols - 1)), 0.0f);
  174. y1 = Math.Max(Math.Min(y1, (float)(image.Rows - 1)), 0.0f);
  175. Cv2.Rectangle(result_image, new OpenCvSharp.Point(x0, y0), new OpenCvSharp.Point(x1, y1), new Scalar(0, 255, 0), 2);
  176. string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
  177. Cv2.PutText(result_image, label, new OpenCvSharp.Point(x0, y0 - 5), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2);
  178. }
  179. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  180. textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";
  181. }
  182. private void pictureBox2_DoubleClick(object sender, EventArgs e)
  183. {
  184. Common.ShowNormalImg(pictureBox2.Image);
  185. }
  186. private void pictureBox1_DoubleClick(object sender, EventArgs e)
  187. {
  188. Common.ShowNormalImg(pictureBox1.Image);
  189. }
  190. }
  191. }

下载

源码下载

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

/ 登录

评论记录:

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

分类栏目

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