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.8f;
            nmsThreshold = 0.5f;

            modelpath = "model/yolo_free_huge_widerface_192x320.onnx";

            inpHeight = 192;
            inpWidth = 320;

            opencv_net = CvDnn.ReadNetFromOnnx(modelpath);

            class_names = new List<string>();
            class_names.Add("face");
            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.8f;nmsThreshold = 0.5f;modelpath = "model/yolo_free_huge_widerface_192x320.onnx";inpHeight = 192;inpWidth = 320;opencv_net = CvDnn.ReadNetFromOnnx(modelpath);class_names = new List<string>();class_names.Add("face");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];  //cxfloat cy = (0.5f + i + pdata[1]) * strides[n];   //cyfloat w = (float)(Math.Exp(pdata[2]) * strides[n]);   //wfloat h = (float)(Math.Exp(pdata[3]) * strides[n]);  //hfloat 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.hqwc.cn/news/325063.html

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

相关文章

基于SSM的人事档案管理系统的设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

C ++类

定义一个Person类&#xff0c;私有成员int age&#xff0c;string &name&#xff0c;定义一个Stu类&#xff0c;包含私有成员double *score&#xff0c;写出两个类的构造函数、析构函数、拷贝构造和拷贝赋值函数&#xff0c;完成对Person的运算符重载(算术运算符、条件运算…

canvas设置图形的阴影

查看专栏目录 canvas示例教程100专栏&#xff0c;提供canvas的基础知识&#xff0c;高级动画&#xff0c;相关应用扩展等信息。canvas作为html的一部分&#xff0c;是图像图标地图可视化的一个重要的基础&#xff0c;学好了canvas&#xff0c;在其他的一些应用上将会起到非常重…

微信小程序:flex布局实现换行

1、关键代码.wxml&#xff1a; <view class"pay margin-top-40"><view class"info"><view class"pay-info-title margin-left-22 flex-start"> 请选择充值金额</view><view class"flex-wrap margin-top-20&quo…

如何在 Ubuntu 20.04 上安装和使用 Docker

前些天发现了一个人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;最重要的屌图甚多&#xff0c;忍不住分享一下给大家。点击跳转到网站。 如何在 Ubuntu 20.04 上安装和使用 Docker 介绍 Docker是一个可以简化容器中应用程序进程管理过程的应用程序。…

数字后端设计实现 | 数字后端PR工具Innovus中如何创建不同高度的row?

吾爱IC社区星球学员问题&#xff1a;Innovus后端实现时两种种不同高度的site能做在一个pr里面吗&#xff1f; 答案是可以的。 Innovus支持在同一个设计中中使用不同的row&#xff0c;但需要给各自子模块创建power domain。这里所说的不同高度的row&#xff0c;有两种情况。 1…

基础面试题整理1

1.面向对象的特点 继承&#xff08;复用性&#xff09;、封装&#xff08;复用性&#xff09;、多态&#xff08;可移植性、灵活性&#xff09; 2.ArrayList与LinkedList区别 ArrayList和LinkedList都是实现了List接口 ArrayList底层是动态数组 LinkedList底层是链表&#…

【EI会议征稿通知】2024年人工智能与电力系统国际学术会议(AIPS 2024)

2024年人工智能与电力系统国际学术会议&#xff08;AIPS 2024&#xff09; 2024 International Conference on Artificial Intelligence and Power System 2024年人工智能与电力系统国际学术会议 (AIPS 2024) 将于2024年04月19日-21日在中国成都召开。AIPS 2024将围绕“人工智…

Python实现某城市从站点API获取天气状况示例(Crossin教室实例24)

一、要点说明&#xff1a; 根据站点当前API数据是由‘\r’字符连接的字符串的特点&#xff0c;主要用到了字符串的split()方法。此方法参数就是‘\r’。函数返回值是被分隔的字符串的列表。通过使用列表索引就可以分项取到天气数据。 二、示例代码&#xff1a; import reque…

操作系统期末复习知识点

目录 一.概论 1.操作系统的介绍 2.特性 3.主要功能 4.作用 二.进程的描述与控制 1.进程的定义 2.特性 3.进程的创建步骤 4.基本状态转化 5.PCB的作用 6.进程与线程的比较 三.进程同步 1.同步的概念&#xff08;挺重要的&#xff09; 2.临界区 3.管程和进程的区…

Spring Boot 整合 Caffeine 本地缓存及 Spring Cache 注解的使用

Spring Boot 整合 Caffeine 本地缓存及 Spring Cache 注解的使用 介绍 在现代的Web应用程序中&#xff0c;缓存是提高性能和响应速度的重要手段之一。Spring Boot提供了对缓存的良好支持&#xff0c;并且可以轻松地整合Caffeine本地缓存作为缓存提供者。结合Spring Cache注解…

DDIA 第十一章:流处理

本文是《数据密集型应用系统设计》&#xff08;DDIA&#xff09;的读书笔记&#xff0c;一共十二章&#xff0c;我已经全部阅读并且整理完毕。 采用一问一答的形式&#xff0c;并且用列表形式整理了原文。 笔记的内容大概是原文的 1/5 ~ 1/3&#xff0c;所以你如果没有很多时间…