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];  //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下载

源码下载

相关推荐
weixin_408266341 分钟前
深度学习-分布式训练机制
人工智能·分布式·深度学习
struggle202512 分钟前
AgenticSeek开源的完全本地的 Manus AI。无需 API,享受一个自主代理,它可以思考、浏览 Web 和编码,只需支付电费。
人工智能·开源·自动化
Panesle13 分钟前
阿里开源通义万相Wan2.1-VACE-14B:用于视频创建和编辑的一体化模型
人工智能·开源·大模型·文生视频·多模态·生成模型
QQ27402875634 分钟前
Kite AI 自动机器人部署教程
linux·运维·服务器·人工智能·机器人·web3
巷9551 小时前
OpenCV光流估计:原理、实现与应用
人工智能·opencv·计算机视觉
说私域1 小时前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的“互相拆台”式宣传策略研究
人工智能·小程序·开源·零售
sbc-study1 小时前
生成对抗网络(Generative Adversarial Networks ,GAN)
人工智能·神经网络·生成对抗网络
m0_620607811 小时前
机器学习——集成学习基础
人工智能·机器学习·集成学习
weixin_549808362 小时前
如何使用易路iBuilder智能体平台快速安全深入实现AI HR【实用帖】
人工智能·安全
EasyDSS2 小时前
WebRTC技术下的EasyRTC音视频实时通话SDK,助力车载通信打造安全高效的智能出行体验
人工智能·音视频