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 人脸检测&人脸图像质量评估

效果

c# form opencvsharp 人脸检测,C#人工智能实践,dnn,人工智能,神经网络,YOLO,c#,计算机视觉,opencv

模型信息

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]
---------------------------------------------------------------

项目

c# form opencvsharp 人脸检测,C#人工智能实践,dnn,人工智能,神经网络,YOLO,c#,计算机视觉,opencv

代码

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

            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;  //形状1x10
            int 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;
        }

    }
}

下载

源码下载文章来源地址https://www.toymoban.com/news/detail-813480.html

到了这里,关于C# OpenCvSharp DNN FreeYOLO 人脸检测&人脸图像质量评估的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • C# OpenCvSharp DNN Image Retouching

    目录 介绍 模型 项目 效果 代码 下载 C# OpenCvSharp DNN Image Retouching github地址:https://github.com/hejingwenhejingwen/CSRNet (ECCV 2020) Conditional Sequential Modulation for Efficient Global Image Retouching Model Properties ------------------------- --------------------------------------------------------------- Inputs -----------------

    2024年02月21日
    浏览(30)
  • C# OpenCvSharp DNN Onnx Demo 资源汇总

    目录 1、OCR 相关 2、人脸、人像、人头 相关 3、物体检测 对象识别相关 4、图像分类、实例分割 姿态识别 5、摄像头相关 6、条码、二维码相关 7、OpencvSharp Demo 8、其他 C# OpenCvSharp DNN Onnx Demo 资源汇总,不定时更新 最新更新时间:2023-11-13 我建了一个QQ群,欢迎大家进群交流 群

    2024年02月05日
    浏览(28)
  • C# OpenCvSharp DNN Low Light image Enhancement

    目录 介绍 效果 模型信息 项目 代码 下载 C# OpenCvSharp DNN Low Light image Enhancement github地址:https://github.com/zhenqifu/PairLIE     Model Properties ------------------------- --------------------------------------------------------------- Inputs ------------------------- name:input tensor:Float[1, 3, 512, 512] name:exposure

    2024年02月21日
    浏览(36)
  • C# OpenCvSharp DNN 二维码增强 超分辨率

    目录 效果 项目 代码 下载  using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using OpenCvSharp; using OpenCvSharp.Dnn; using OpenCvSharp.Extensions; namespace OpenCvSharp_DNN_二维码增强 {     public partial cl

    2024年02月12日
    浏览(30)
  • LabVIEW快速实现OpenCV DNN(YunNet)的人脸检测(含源码)

    ‍‍🏡博客主页: virobotics的CSDN博客:LabVIEW深度学习、人工智能博主 🎄所属专栏:『LabVIEW深度学习实战』 🍻上期文章: LabVIEW AI视觉工具包OpenCV Mat基本用法和属性 📰如觉得博主文章写的不错或对你有所帮助的话,还望大家多多支持呀! 欢迎大家✌关注、👍点赞、✌收

    2024年02月09日
    浏览(37)
  • 图像质量评估(3) -- 噪声

            图像中的噪声是一些原始场景并未携带的内容,图像领域很多时候用瑕疵(artifacts)来表达其影响。通常来说,噪声是由随机过程造成的测量的统计偏差。在图像领域,噪声表现为图像中的瑕疵,看上去就像是覆盖在图像上的颗粒物。在一副图像内,噪声有不同的

    2024年02月06日
    浏览(25)
  • C# OpenCvSharp 轮廓检测

    目录 效果 代码 下载  using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using OpenCvSharp; using OpenCvSharp.Extensions; namespace OpenCvSharp_轮廓检测 {     public partial class Form1 : Form     {        

    2024年04月15日
    浏览(35)
  • C# OpenCvSharp 图像校正

    目录 效果 代码 下载 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using OpenCvSharp; using OpenCvSharp.Extensions; namespace OpenCvSharp_图像校正 {     public partial class Form1 : Form     {         pu

    2024年02月15日
    浏览(28)
  • 图像质量评估(5) -- 畸变(Distortion)

            当图像中原本应该是直线的地方看起来发生了不自然的变形或扭曲时,我们称为图像畸变。有三种类型的镜头畸变:桶形畸变(后文使用英文barrel),枕形畸变(后文使用pincushion)和胡子畸变(后文使用英文wave或mustache,这种畸变里包含了桶形畸变和枕形畸变)

    2024年02月05日
    浏览(24)
  • c# OpenCvSharp 检测(斑点检测、边缘检测、轮廓检测)(五)

    在C#中使用OpenCV进行图像处理时,可以使用不同的算法和函数来实现斑点检测、边缘检测和轮廓检测。 斑点检测 边缘检测 轮廓检测 斑点检测是指在图像中找到明亮或暗的小区域(通常表示为斑点),并标记它们的位置。可以使用OpenCV中的函数SimpleBlobDetector来实现斑点检测。

    2024年02月04日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包