首页 最新 热门 推荐

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

C# OpenCvSharp DNN FreeYOLO 密集行人检测

  • 25-02-19 03:00
  • 4067
  • 9861
blog.csdn.net

目录

效果

模型信息

项目

代码

下载


C# OpenCvSharp DNN FreeYOLO 密集行人检测

效果

模型信息

Inputs
-------------------------
name:input
tensor:Float[1, 3, 192, 320]
---------------------------------------------------------------

Outputs
-------------------------
name:output
tensor:Float[1, 1260, 6]
---------------------------------------------------------------

项目

代码

using OpenCvSharp;
using OpenCvSharp.Dnn;
using System;
using System.Collections.Generic;
using System.Drawing;
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 confThreshold;
        float nmsThreshold;

        int num_stride = 3;
        float[] strides = new float[3] { 8.0f, 16.0f, 32.0f };

        string modelpath;

        int inpHeight;
        int inpWidth;

        List class_names;
        int num_class;

        Net opencv_net;
        Mat BN_image;

        Mat image;
        Mat result_image;

        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)
        {
            confThreshold = 0.6f;
            nmsThreshold = 0.5f;

            modelpath = "model/yolo_free_huge_crowdhuman_192x320.onnx";

            inpHeight = 192;
            inpWidth = 320;

            opencv_net = CvDnn.ReadNetFromOnnx(modelpath);

            class_names = new List();
            class_names.Add("person");
            num_class = 1;

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

        }

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

            float ratio = Math.Min(1.0f * inpHeight / image.Rows, 1.0f * inpWidth / image.Cols);
            int neww = (int)(image.Cols * ratio);
            int newh = (int)(image.Rows * ratio);

            Mat dstimg = new Mat();
            Cv2.Resize(image, dstimg, new OpenCvSharp.Size(neww, newh));

            Cv2.CopyMakeBorder(dstimg, dstimg, 0, inpHeight - newh, 0, inpWidth - neww, BorderTypes.Constant);

            BN_image = CvDnn.BlobFromImage(dstimg);

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

            //模型推理,读取推理结果
            Mat[] outs = new Mat[1] { 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);
            int nout = outs[0].Size(2);

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

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

            for (int n = 0; n < num_stride; n++)
            {
                int num_grid_x = (int)Math.Ceiling(inpWidth / strides[n]);
                int num_grid_y = (int)Math.Ceiling(inpHeight / strides[n]);

                for (int i = 0; i < num_grid_y; i++)
                {
                    for (int j = 0; j < num_grid_x; j++)
                    {
                        float box_score = pdata[4];
                        int max_ind = 0;
                        float max_class_socre = 0;
                        for (int k = 0; k < num_class; k++)
                        {
                            if (pdata[k + 5] > max_class_socre)
                            {
                                max_class_socre = pdata[k + 5];
                                max_ind = k;
                            }
                        }
                        max_class_socre = max_class_socre* box_score;
                        max_class_socre = (float)Math.Sqrt(max_class_socre);

                        if (max_class_socre > confThreshold)
                        {
                            float cx = (0.5f + j + pdata[0]) * strides[n];  //cx
                            float cy = (0.5f + i + pdata[1]) * strides[n];   //cy
                            float w = (float)(Math.Exp(pdata[2]) * strides[n]);   //w
                            float h = (float)(Math.Exp(pdata[3]) * strides[n]);  //h

                            float xmin = (float)((cx - 0.5 * w) / ratio);
                            float ymin = (float)((cy - 0.5 * h) / ratio);
                            float xmax = (float)((cx + 0.5 * w) / ratio);
                            float ymax = (float)((cy + 0.5 * h) / ratio);

                            int left = (int)((cx - 0.5 * w) / ratio);
                            int top = (int)((cy - 0.5 * h) / ratio);
                            int width = (int)(w / ratio);
                            int height = (int)(h / ratio);

                            confidences.Add(max_class_socre);
                            boxes.Add(new Rect(left, top, width, height));
                            classIds.Add(max_ind);
                        }
                        pdata += nout;
                    }
                }

            }

            int[] indices;
            CvDnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, out indices);

            result_image = image.Clone();

            for (int ii = 0; ii < indices.Length; ++ii)
            {
                int idx = indices[ii];
                Rect box = boxes[idx];
                Cv2.Rectangle(result_image, new OpenCvSharp.Point(box.X, box.Y), new OpenCvSharp.Point(box.X + box.Width, box.Y + box.Height), new Scalar(0, 0, 255), 2);
                string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
                Cv2.PutText(result_image, label, new OpenCvSharp.Point(box.X, box.Y - 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.Linq;
  7. using System.Windows.Forms;
  8. namespace OpenCvSharp_DNN_Demo
  9. {
  10. public partial class frmMain : Form
  11. {
  12. public frmMain()
  13. {
  14. InitializeComponent();
  15. }
  16. string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
  17. string image_path = "";
  18. DateTime dt1 = DateTime.Now;
  19. DateTime dt2 = DateTime.Now;
  20. float confThreshold;
  21. float nmsThreshold;
  22. int num_stride = 3;
  23. float[] strides = new float[3] { 8.0f, 16.0f, 32.0f };
  24. string modelpath;
  25. int inpHeight;
  26. int inpWidth;
  27. List<string> class_names;
  28. int num_class;
  29. Net opencv_net;
  30. Mat BN_image;
  31. Mat image;
  32. Mat result_image;
  33. private void button1_Click(object sender, EventArgs e)
  34. {
  35. OpenFileDialog ofd = new OpenFileDialog();
  36. ofd.Filter = fileFilter;
  37. if (ofd.ShowDialog() != DialogResult.OK) return;
  38. pictureBox1.Image = null;
  39. pictureBox2.Image = null;
  40. textBox1.Text = "";
  41. image_path = ofd.FileName;
  42. pictureBox1.Image = new Bitmap(image_path);
  43. image = new Mat(image_path);
  44. }
  45. private void Form1_Load(object sender, EventArgs e)
  46. {
  47. confThreshold = 0.6f;
  48. nmsThreshold = 0.5f;
  49. modelpath = "model/yolo_free_huge_crowdhuman_192x320.onnx";
  50. inpHeight = 192;
  51. inpWidth = 320;
  52. opencv_net = CvDnn.ReadNetFromOnnx(modelpath);
  53. class_names = new List<string>();
  54. class_names.Add("person");
  55. num_class = 1;
  56. image_path = "test_img/1.jpg";
  57. pictureBox1.Image = new Bitmap(image_path);
  58. }
  59. private unsafe void button2_Click(object sender, EventArgs e)
  60. {
  61. if (image_path == "")
  62. {
  63. return;
  64. }
  65. textBox1.Text = "检测中,请稍等……";
  66. pictureBox2.Image = null;
  67. Application.DoEvents();
  68. image = new Mat(image_path);
  69. float ratio = Math.Min(1.0f * inpHeight / image.Rows, 1.0f * inpWidth / image.Cols);
  70. int neww = (int)(image.Cols * ratio);
  71. int newh = (int)(image.Rows * ratio);
  72. Mat dstimg = new Mat();
  73. Cv2.Resize(image, dstimg, new OpenCvSharp.Size(neww, newh));
  74. Cv2.CopyMakeBorder(dstimg, dstimg, 0, inpHeight - newh, 0, inpWidth - neww, BorderTypes.Constant);
  75. BN_image = CvDnn.BlobFromImage(dstimg);
  76. //配置图片输入数据
  77. opencv_net.SetInput(BN_image);
  78. //模型推理,读取推理结果
  79. Mat[] outs = new Mat[1] { new Mat() };
  80. string[] outBlobNames = opencv_net.GetUnconnectedOutLayersNames().ToArray();
  81. dt1 = DateTime.Now;
  82. opencv_net.Forward(outs, outBlobNames);
  83. dt2 = DateTime.Now;
  84. int num_proposal = outs[0].Size(1);
  85. int nout = outs[0].Size(2);
  86. float* pdata = (float*)outs[0].Data;
  87. List<float> confidences = new List<float>();
  88. List<Rect> boxes = new List<Rect>();
  89. List<int> classIds = new List<int>();
  90. for (int n = 0; n < num_stride; n++)
  91. {
  92. int num_grid_x = (int)Math.Ceiling(inpWidth / strides[n]);
  93. int num_grid_y = (int)Math.Ceiling(inpHeight / strides[n]);
  94. for (int i = 0; i < num_grid_y; i++)
  95. {
  96. for (int j = 0; j < num_grid_x; j++)
  97. {
  98. float box_score = pdata[4];
  99. int max_ind = 0;
  100. float max_class_socre = 0;
  101. for (int k = 0; k < num_class; k++)
  102. {
  103. if (pdata[k + 5] > max_class_socre)
  104. {
  105. max_class_socre = pdata[k + 5];
  106. max_ind = k;
  107. }
  108. }
  109. max_class_socre = max_class_socre* box_score;
  110. max_class_socre = (float)Math.Sqrt(max_class_socre);
  111. if (max_class_socre > confThreshold)
  112. {
  113. float cx = (0.5f + j + pdata[0]) * strides[n]; //cx
  114. float cy = (0.5f + i + pdata[1]) * strides[n]; //cy
  115. float w = (float)(Math.Exp(pdata[2]) * strides[n]); //w
  116. float h = (float)(Math.Exp(pdata[3]) * strides[n]); //h
  117. float xmin = (float)((cx - 0.5 * w) / ratio);
  118. float ymin = (float)((cy - 0.5 * h) / ratio);
  119. float xmax = (float)((cx + 0.5 * w) / ratio);
  120. float ymax = (float)((cy + 0.5 * h) / ratio);
  121. int left = (int)((cx - 0.5 * w) / ratio);
  122. int top = (int)((cy - 0.5 * h) / ratio);
  123. int width = (int)(w / ratio);
  124. int height = (int)(h / ratio);
  125. confidences.Add(max_class_socre);
  126. boxes.Add(new Rect(left, top, width, height));
  127. classIds.Add(max_ind);
  128. }
  129. pdata += nout;
  130. }
  131. }
  132. }
  133. int[] indices;
  134. CvDnn.NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, out indices);
  135. result_image = image.Clone();
  136. for (int ii = 0; ii < indices.Length; ++ii)
  137. {
  138. int idx = indices[ii];
  139. Rect box = boxes[idx];
  140. Cv2.Rectangle(result_image, new OpenCvSharp.Point(box.X, box.Y), new OpenCvSharp.Point(box.X + box.Width, box.Y + box.Height), new Scalar(0, 0, 255), 2);
  141. string label = class_names[classIds[idx]] + ":" + confidences[idx].ToString("0.00");
  142. Cv2.PutText(result_image, label, new OpenCvSharp.Point(box.X, box.Y - 5), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2);
  143. }
  144. pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
  145. textBox1.Text = "推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms";
  146. }
  147. private void pictureBox2_DoubleClick(object sender, EventArgs e)
  148. {
  149. Common.ShowNormalImg(pictureBox2.Image);
  150. }
  151. private void pictureBox1_DoubleClick(object sender, EventArgs e)
  152. {
  153. Common.ShowNormalImg(pictureBox1.Image);
  154. }
  155. }
  156. }

下载

可执行程序exe下载

源码下载

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

/ 登录

评论记录:

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

分类栏目

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