C# OpenCvSharp DNN FreeYOLO 密集行人检测

目录

效果

模型信息

项目

代码

下载


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<string> 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<string>();
            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<float> confidences = new List<float>();
            List<Rect> boxes = new List<Rect>();
            List<int> classIds = new List<int>();

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

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<string> 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<string>();
            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<float> confidences = new List<float>();
            List<Rect> boxes = new List<Rect>();
            List<int> classIds = new List<int>();

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

下载

可执行程序exe下载

源码下载


http://www.niftyadmin.cn/n/5307134.html

相关文章

数据结构OJ实验14-哈希查找

A. DS哈希查找—线性探测再散列 题目描述 定义哈希函数为H(key) key%11&#xff0c;输入表长&#xff08;大于、等于11&#xff09;。输入关键字集合&#xff0c;用线性探测再散列构建哈希表&#xff0c;并查找给定关键字。 输入 测试次数t 每组测试数据为&#xff1a; …

篮球羽毛球乒乓球体育场馆预订小程序开发

开发一款专业的小程序&#xff0c;用于多场馆场地的预定和管理&#xff0c;包括体育馆、羽毛球馆、兵乒球馆、篮球馆等各类场馆。此小程序旨在为场馆提供全方位的运营解决方案&#xff0c;并满足会员的不同需求。 该小程序的核心功能特性包括&#xff1a; 场馆管理&#xff…

数据结构 模拟实现LinkedList双向不循环链表

目录 一、双向不循环链表的概念 二、链表的接口 三、链表的方法实现 &#xff08;1&#xff09;display方法 &#xff08;2&#xff09;size方法 &#xff08;3&#xff09;contains方法 &#xff08;4&#xff09;addFirst方法 &#xff08;5&#xff09;addLast方法 …

安卓拍照扫描APP解决方案——基于深度学习的文本方向检测与校正

简介 在OCR&#xff08;光学字符识别&#xff09;系统中&#xff0c;为了提高OCR系统的性能&#xff0c;确保准确识别文本内容。图像预处理是一个关键的组成部分。其中&#xff0c;一个重要的任务是矫正文本方向。例如&#xff0c;在进行文字识别时&#xff0c;不仅需要有效地…

C#,归并排序算法(Merge Sort Algorithm)的源代码及数据可视化

归并排序 归并算法采用非常经典的分治策略&#xff0c;每次把序列分成n/2的长度&#xff0c;将问题分解成小问题&#xff0c;由复杂变简单。 因为使用了递归算法&#xff0c;不能用于大数据的排序。 核心代码&#xff1a; using System; using System.Text; using System.Co…

JAVAEE初阶相关内容第二十弹--HTTP协议【续集】

写在前&#xff1a;在前一篇博客中我们初步掌握了HTTP(超文本传输协议)的相关知识【点击跳转】&#xff0c;认识了HYYP协议的工作过程&#xff0c;掌握抓包工具Fiddler的使用。在“方法”中重点需要理解“GET”方法与“POST”方法的格式与内容&#xff0c;并了解了请求“报头”…

读书之深入理解ffmpeg_简单笔记3(初步)

通读完只能对书中内容有大概的了解&#xff0c;具体的细节还得一一实践攻克。 10: libavformat接口使用 媒体流&#xff0c;文件等封装&#xff0c;解封装&#xff0c;转封装 视频截取&#xff0c;AVFormatContext,AVPacket等介绍 11&#xff1a;libavcodec接口使用 视频&…

Linux第9步_通过终端查看U盘文件

学习完“USB设置”后&#xff0c;我们学习通过终端来查看U盘文件。前面讲解过使用鼠标打开U盘&#xff0c;但是在实际使用中&#xff0c;更多的还是采用命令来实现对U盘的操作。 1、在桌面&#xff0c;右击鼠标&#xff0c;弹出下面的界面: 2、点击上图中的“打开终端”&#…