C# OpenCvSharp DNN FreeYOLO 人脸检测人脸图像质量评估

本文主要是介绍C# OpenCvSharp DNN FreeYOLO 人脸检测人脸图像质量评估,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

效果

模型信息

yolo_free_huge_widerface_192x320.onnx

face-quality-assessment.onnx

项目

代码

frmMain.cs

FreeYoloFace

FaceQualityAssessment.cs

下载


C# OpenCvSharp DNN FreeYOLO 人脸检测&人脸图像质量评估

效果

模型信息

yolo_free_huge_widerface_192x320.onnx


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

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

face-quality-assessment.onnx

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

Outputs
-------------------------
name:quality
tensor:Float[1, 10]
---------------------------------------------------------------

项目

代码

frmMain.cs

using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
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;

        StringBuilder sb = new StringBuilder();

        Mat image;
        Mat result_image;

        FaceQualityAssessment fqa = new FaceQualityAssessment("model/face-quality-assessment.onnx");
        FreeYoloFace face = new FreeYoloFace("model/yolo_free_huge_widerface_192x320.onnx");

        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)
        {
            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 = "检测中,请稍等……";
            if (pictureBox2.Image != null)
            {
                pictureBox2.Image.Dispose();
            }
            pictureBox2.Image = null;
            sb.Clear();
            Application.DoEvents();

            image = new Mat(image_path);

            dt1 = DateTime.Now;
            List<Face> ltFace = face.Detect(image);
            dt2 = DateTime.Now;

            if (ltFace.Count > 0)
            {
                sb.AppendLine("推理耗时:" + (dt2 - dt1).TotalMilliseconds + "ms");
                result_image = image.Clone();
                foreach (var item in ltFace)
                {
                    Mat crop_img = new Mat(image, item.rect);
                    float fqa_prob_mean = fqa.Detect(crop_img);
                    crop_img.Dispose();
                    Cv2.Rectangle(result_image, new OpenCvSharp.Point(item.rect.X, item.rect.Y), new OpenCvSharp.Point(item.rect.X + item.rect.Width, item.rect.Y + item.rect.Height), new Scalar(0, 0, 255), 2);
                    string label = "prob:" + item.prob.ToString("0.00") + " fqa_score:" + fqa_prob_mean.ToString("0.00");
                    sb.AppendLine(label);
                    Cv2.PutText(result_image, label, new OpenCvSharp.Point(item.rect.X, item.rect.Y - 5), HersheyFonts.HersheySimplex, 1, new Scalar(0, 0, 255), 2);
                }
                pictureBox2.Image = new Bitmap(result_image.ToMemoryStream());
                textBox1.Text = sb.ToString();
            }
            else
            {
                textBox1.Text = "未检测到人脸";
            }
        }

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

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

FreeYoloFace.cs

using OpenCvSharp.Dnn;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;namespace OpenCvSharp_DNN_Demo
{public class FreeYoloFace{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;public FreeYoloFace(string modelpath){opencv_net = CvDnn.ReadNetFromOnnx(modelpath);class_names = new List<string> { "face" };num_class = 1;confThreshold = 0.8f;nmsThreshold = 0.5f;inpHeight = 192;inpWidth = 320;}unsafe public List<Face> Detect(Mat image){List<Face> ltFace = new List<Face>();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();opencv_net.Forward(outs, outBlobNames);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);for (int ii = 0; ii < indices.Length; ++ii){int idx = indices[ii];Rect box = boxes[idx];ltFace.Add(new Face(box, confidences[idx]));}outs[0].Dispose();BN_image.Dispose();dstimg.Dispose();return ltFace;}}
}

FaceQualityAssessment.cs

using OpenCvSharp;
using OpenCvSharp.Dnn;
using System.Linq;namespace OpenCvSharp_DNN_Demo
{public class FaceQualityAssessment{Net net;int inpWidth = 112;int inpHeight = 112;float[] mean = new float[] { 0.5f, 0.5f, 0.5f };float[] std = new float[] { 0.5f, 0.5f, 0.5f };public FaceQualityAssessment(string modelpath){net = CvDnn.ReadNetFromOnnx(modelpath);}unsafe public float Detect(Mat cropped){Mat rgbimg = new Mat();Cv2.CvtColor(cropped, rgbimg, ColorConversionCodes.BGR2RGB);Cv2.Resize(rgbimg, rgbimg, new Size(inpWidth, inpHeight));Mat normalized_mat = Normalize(rgbimg);Mat blob = CvDnn.BlobFromImage(normalized_mat);//配置图片输入数据net.SetInput(blob);//模型推理,读取推理结果Mat[] outs = new Mat[1] { new Mat() };string[] outBlobNames = net.GetUnconnectedOutLayersNames().ToArray();net.Forward(outs, outBlobNames);float* pdata = (float*)outs[0].Data;  //形状1x10int length = outs[0].Size(1);float fqa_prob_mean = 0;for (int i = 0; i < length; i++){fqa_prob_mean += pdata[i];}fqa_prob_mean /= length;rgbimg.Dispose();normalized_mat.Dispose();blob.Dispose();outs[0].Dispose();return fqa_prob_mean;}Mat Normalize(Mat src){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;}}
}

下载

源码下载

这篇关于C# OpenCvSharp DNN FreeYOLO 人脸检测人脸图像质量评估的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/590114

相关文章

C#实现千万数据秒级导入的代码

《C#实现千万数据秒级导入的代码》在实际开发中excel导入很常见,现代社会中很容易遇到大数据处理业务,所以本文我就给大家分享一下千万数据秒级导入怎么实现,文中有详细的代码示例供大家参考,需要的朋友可... 目录前言一、数据存储二、处理逻辑优化前代码处理逻辑优化后的代码总结前言在实际开发中excel导入很

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法

MySQL8 密码强度评估与配置详解

《MySQL8密码强度评估与配置详解》MySQL8默认启用密码强度插件,实施MEDIUM策略(长度8、含数字/字母/特殊字符),支持动态调整与配置文件设置,推荐使用STRONG策略并定期更新密码以提... 目录一、mysql 8 密码强度评估机制1.核心插件:validate_password2.密码策略级

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

C#文件复制异常:"未能找到文件"的解决方案与预防措施

《C#文件复制异常:未能找到文件的解决方案与预防措施》在C#开发中,文件操作是基础中的基础,但有时最基础的File.Copy()方法也会抛出令人困惑的异常,当targetFilePath设置为D:2... 目录一个看似简单的文件操作问题问题重现与错误分析错误代码示例错误信息根本原因分析全面解决方案1. 确保

基于C#实现PDF转图片的详细教程

《基于C#实现PDF转图片的详细教程》在数字化办公场景中,PDF文件的可视化处理需求日益增长,本文将围绕Spire.PDFfor.NET这一工具,详解如何通过C#将PDF转换为JPG、PNG等主流图片... 目录引言一、组件部署二、快速入门:PDF 转图片的核心 C# 代码三、分辨率设置 - 清晰度的决定因

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

C#高效实现Word文档内容查找与替换的6种方法

《C#高效实现Word文档内容查找与替换的6种方法》在日常文档处理工作中,尤其是面对大型Word文档时,手动查找、替换文本往往既耗时又容易出错,本文整理了C#查找与替换Word内容的6种方法,大家可以... 目录环境准备方法一:查找文本并替换为新文本方法二:使用正则表达式查找并替换文本方法三:将文本替换为图

Python脚本轻松实现检测麦克风功能

《Python脚本轻松实现检测麦克风功能》在进行音频处理或开发需要使用麦克风的应用程序时,确保麦克风功能正常是非常重要的,本文将介绍一个简单的Python脚本,能够帮助我们检测本地麦克风的功能,需要的... 目录轻松检测麦克风功能脚本介绍一、python环境准备二、代码解析三、使用方法四、知识扩展轻松检测麦