C# DlibDotNet 人脸识别、人脸68特征点识别、人脸5特征点识别、人脸对齐,三角剖分,人脸特征比对

人脸识别


人脸68特征点识别

人脸5特征点识别


人脸对齐

三角剖分

人脸特征比对

项目

VS2022+.net4.8+OpenCvSharp4+DlibDotNet

Demo下载

代码

using DlibDotNet.Extensions;
using DlibDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using OpenCvSharp;
using System.Drawing.Imaging;
using System.Globalization;

namespace DlibDotNet_人脸识别_人脸68特征点识别_人脸5特征点识别
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
        string imgPath = "";
        string imgPath2 = "";
        string startupPath = "";


        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;

            pictureBox1.Image = null;

            imgPath = ofd.FileName;
            pictureBox1.Image = new Bitmap(imgPath);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() != DialogResult.OK) return;

            pictureBox2.Image = null;

            imgPath2 = ofd.FileName;
            pictureBox2.Image = new Bitmap(imgPath2);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string startupPath = Application.StartupPath;
            Dlib.Encoding = Environment.OSVersion.Platform == PlatformID.Win32NT ? Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.ANSICodePage) : Encoding.UTF8;

        }

        /// <summary>
        /// 人脸识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {

            if (imgPath == "")
            {
                return;
            }

            using (var faceDetector = Dlib.GetFrontalFaceDetector())
            using (var image = Dlib.LoadImage<RgbPixel>(imgPath))
            {
                var dets = faceDetector.Operator(image);
                foreach (var r in dets)
                    Dlib.DrawRectangle(image, r, new RgbPixel { Green = 255 });

                var result = image.ToBitmap();
                this.pictureBox1.Invoke(new Action(() =>
                {
                    this.pictureBox1.Image?.Dispose();
                    this.pictureBox1.Image = result;
                }));
            }

        }

        /// <summary>
        /// 5特征点识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            if (imgPath == "")
            {
                return;
            }

            string faceDataPath = "shape_predictor_5_face_landmarks.dat";

            Mat mat = new Mat(imgPath);

            Bitmap bmp = new Bitmap(imgPath);
            bmp = Get24bppRgb(bmp);

            // 图像转换到Dlib的图像类中
            Array2D<RgbPixel> img = DlibDotNet.Extensions.BitmapExtensions.ToArray2D<RgbPixel>(bmp);
            var faceDetector = Dlib.GetFrontalFaceDetector();
            var shapePredictor = ShapePredictor.Deserialize(faceDataPath);

            // 检测人脸
            var faces = faceDetector.Operator(img);

            if (faces.Count() == 0) { return; }

            // 人脸区域中识别脸部特征
            var shape = shapePredictor.Detect(img, faces[0]);

            var bradleyPoints = (from i in Enumerable.Range(0, (int)shape.Parts)
                                 let p = shape.GetPart((uint)i)
                                 select new OpenCvSharp.Point(p.X, p.Y)).ToArray();

            foreach (var item in bradleyPoints)
            {
                Cv2.Circle(mat, item.X, item.Y, 2, Scalar.Green, 2);
            }

            pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
        }

        // Convert to Format24bppRgb
        private static Bitmap Get24bppRgb(System.Drawing.Image image)
        {
            var bitmap = new Bitmap(image);
            var bitmap24 = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);
            using (var gr = Graphics.FromImage(bitmap24))
            {
                gr.DrawImage(bitmap, new System.Drawing.Rectangle(0, 0, bitmap24.Width, bitmap24.Height));
            }
            return bitmap24;
        }

        /// <summary>
        /// 68特征点识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            if (imgPath == "")
            {
                return;
            }

            string faceDataPath = "shape_predictor_68_face_landmarks.dat";

            Mat mat = new Mat(imgPath);

            Bitmap bmp = new Bitmap(imgPath);
            bmp = Get24bppRgb(bmp);

            // 图像转换到Dlib的图像类中
            Array2D<RgbPixel> img = DlibDotNet.Extensions.BitmapExtensions.ToArray2D<RgbPixel>(bmp);
            var faceDetector = Dlib.GetFrontalFaceDetector();
            var shapePredictor = ShapePredictor.Deserialize(faceDataPath);

            // 检测人脸
            var faces = faceDetector.Operator(img);

            if (faces.Count() == 0) { return; }

            // 人脸区域中识别脸部特征
            var shape = shapePredictor.Detect(img, faces[0]);

            var bradleyPoints = (from i in Enumerable.Range(0, (int)shape.Parts)
                                 let p = shape.GetPart((uint)i)
                                 select new OpenCvSharp.Point(p.X, p.Y)).ToArray();

            foreach (var item in bradleyPoints)
            {
                Cv2.Circle(mat, item.X, item.Y, 2, Scalar.Green, 2);
            }

            pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);
        }

        /// <summary>
        /// 人脸对齐
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            if (imgPath == "")
            {
                return;
            }
            var path = imgPath;
            string faceDataPath = "shape_predictor_68_face_landmarks.dat";
            using (var faceDetector = Dlib.GetFrontalFaceDetector())
            using (var img = Dlib.LoadImage<RgbPixel>(path))
            {
                Dlib.PyramidUp(img);
                var shapePredictor = ShapePredictor.Deserialize(faceDataPath);
                var dets = faceDetector.Operator(img);
                var shapes = new List<FullObjectDetection>();
                foreach (var rect in dets)
                {
                    var shape = shapePredictor.Detect(img, rect);
                    if (shape.Parts <= 2)
                        continue;
                    shapes.Add(shape);
                }

                if (shapes.Any())
                {
                    var lines = Dlib.RenderFaceDetections(shapes);
                    foreach (var line in lines)
                        Dlib.DrawLine(img, line.Point1, line.Point2, new RgbPixel
                        {
                            Green = 255
                        });

                    var wb = img.ToBitmap();
                    this.pictureBox1.Image?.Dispose();
                    this.pictureBox1.Image = wb;
                    foreach (var l in lines)
                        l.Dispose();
                    var chipLocations = Dlib.GetFaceChipDetails(shapes);
                    using (var faceChips = Dlib.ExtractImageChips<RgbPixel>(img, chipLocations))
                    using (var tileImage = Dlib.TileImages(faceChips))
                    {
                        // It is NOT necessary to re-convert WriteableBitmap to Matrix.
                        // This sample demonstrate converting managed image class to
                        // dlib class and vice versa.
                        using (var tile = tileImage.ToBitmap())
                        using (var mat = tile.ToMatrix<RgbPixel>())
                        {
                            var tile2 = mat.ToBitmap();
                            this.pictureBox1.Image?.Dispose();
                            this.pictureBox1.Image = tile2;
                        }
                    }

                    foreach (var c in chipLocations)
                        c.Dispose();
                }

                foreach (var s in shapes)
                    s.Dispose();
            }
        }

        /// <summary>
        /// 人脸特征比对
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";

            if (imgPath == "" || imgPath2 == "")
            {
                return;
            }

            var detector = Dlib.GetFrontalFaceDetector();
            var sp = ShapePredictor.Deserialize("shape_predictor_5_face_landmarks.dat");
            var net = DlibDotNet.Dnn.LossMetric.Deserialize("dlib_face_recognition_resnet_model_v1.dat");


            var img1 = Dlib.LoadImageAsMatrix<RgbPixel>(imgPath);
            var img2 = Dlib.LoadImageAsMatrix<RgbPixel>(imgPath2);

            var faces = new List<Matrix<RgbPixel>>();
            foreach (var face in detector.Operator(img1))
            {
                var shape = sp.Detect(img1, face);
                var faceChipDetail = Dlib.GetFaceChipDetails(shape, 150, 0.25);
                var faceChip = Dlib.ExtractImageChip<RgbPixel>(img1, faceChipDetail);
                faces.Add(faceChip);
            }

            foreach (var face in detector.Operator(img2))
            {
                var shape = sp.Detect(img2, face);
                var faceChipDetail = Dlib.GetFaceChipDetails(shape, 150, 0.25);
                var faceChip = Dlib.ExtractImageChip<RgbPixel>(img2, faceChipDetail);
                faces.Add(faceChip);
            }

            if (faces.Count != 2)
            {
                return;
            }

            var faceDescriptors = net.Operator(faces);

            // Faces are connected in the graph if they are close enough.  Here we check if
            // the distance between two face descriptors is less than 0.6, which is the
            // decision threshold the network was trained to use.  Although you can
            // certainly use any other threshold you find useful.
            var diff = faceDescriptors[1] - faceDescriptors[0];
            float len = Dlib.Length(diff);

            String str = "";
            if (len < 0.6)
            {
                str += "图片1和图片2距离:" + len.ToString() + "   是一个人" + "\r\n";
            }
            else
            {
                str += "图片1和图片2距离:" + len.ToString() + "   不是一个人" + "\r\n";
            }

            str += "图片1特征值:[" + faceDescriptors[0].ToString() + "]\r\n";
            str += "图片2特征值:[" + faceDescriptors[1].ToString() + "]\r\n";

            textBox1.Text = str;

        }

        /// <summary>
        /// 三角剖分
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {

            if (imgPath == "")
            {
                return;
            }

            string faceDataPath = "shape_predictor_68_face_landmarks.dat";
            Mat mat = new Mat(imgPath);
            Bitmap bmp = new Bitmap(imgPath);
            bmp = Get24bppRgb(bmp);
            // 图像转换到Dlib的图像类中
            Array2D<RgbPixel> img = DlibDotNet.Extensions.BitmapExtensions.ToArray2D<RgbPixel>(bmp);
            var faceDetector = Dlib.GetFrontalFaceDetector();
            var shapePredictor = ShapePredictor.Deserialize(faceDataPath);
            // 检测人脸
            var faces = faceDetector.Operator(img);
            if (faces.Count() == 0)
            {
                return;
            }
            // 人脸区域中识别脸部特征
            var shape = shapePredictor.Detect(img, faces[0]);

            var bradleyPoints = (from i in Enumerable.Range(0, (int)shape.Parts)
                                 let p = shape.GetPart((uint)i)
                                 select new OpenCvSharp.Point(p.X, p.Y)).ToArray();

            pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);

            //凸包提取
            var hull = Cv2.ConvexHullIndices(bradleyPoints);
            var bradleyHull = (from i in hull
                               select bradleyPoints[i]).ToArray();

            for (int i = 0; i < bradleyHull.Length - 1; i++)
            {
                Cv2.Line(mat, bradleyHull[i].X, bradleyHull[i].Y, bradleyHull[i + 1].X, bradleyHull[i + 1].Y, Scalar.Red);
            }
            Cv2.Line(mat, bradleyHull[bradleyHull.Length - 1].X, bradleyHull[bradleyHull.Length - 1].Y, bradleyHull[0].X, bradleyHull[0].Y, Scalar.Red);

            pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);

            RotatedRect minAreaRect = Cv2.MinAreaRect(bradleyPoints);
            //三角剖分
            Subdiv2D subdiv = new Subdiv2D();
            Rect rect = new Rect(0, 0, pictureBox1.Image.Width, pictureBox1.Image.Height);
            subdiv.InitDelaunay(rect);

            // 添加与绘制特征点
            for (int i = 0; i < bradleyPoints.Length; i++)
            {
                subdiv.Insert(new Point2f(bradleyPoints[i].X, bradleyPoints[i].Y));
            }
            // 生成剖分三角形
            Vec6f[] triangleList = subdiv.GetTriangleList();
            OpenCvSharp.Point[] pt = new OpenCvSharp.Point[3];
            // 绘制剖分三角形
            for (int i = 0; i < triangleList.Length; i++)
            {
                Vec6f t = triangleList[i];
                pt[0] = new OpenCvSharp.Point((int)t[0], (int)t[1]);
                pt[1] = new OpenCvSharp.Point((int)t[2], (int)t[3]);
                pt[2] = new OpenCvSharp.Point((int)t[4], (int)t[5]);

                Cv2.Line(mat, pt[0], pt[1], Scalar.Green, 1);
                Cv2.Line(mat, pt[1], pt[2], Scalar.Green, 1);
                Cv2.Line(mat, pt[2], pt[1], Scalar.Green, 1);
            }

            pictureBox1.Image = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat);

        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/42131.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

第六章:string类

系列文章目录 文章目录 系列文章目录前言为什么学习string类C语言中的字符串ASCIIUnicode**UTF-8**UTF-16UTF-32 GBK 标准库中的string类string类总结 string类的常用接口说明1. string类对象的常见构造2. string类对象的容量操作3. string类对象的访问及遍历操作4. string类对…

Nginx正向代理和反向代理详解

目录 一、什么是正向代理&#xff1f; 二、什么是反向代理&#xff1f; 三、正向代理和反向代理的作用 一、什么是正向代理&#xff1f; 正向代理&#xff0c;“它代理的是客户端”&#xff0c;是一个位于客户端和目标服务器之间的服务器&#xff0c;为了从目标服务器取得内…

Spring Cloud+Spring Boot+Mybatis+uniapp+前后端分离实现知识付费平台

Java版知识付费-轻松拥有知识付费平台 多种直播形式&#xff0c;全面满足直播场景需求 公开课、小班课、独立直播间等类型&#xff0c;满足讲师个性化直播场景需求&#xff1b;低延迟、双向视频&#xff0c;亲密互动&#xff0c;无论是互动、答疑&#xff0c;还是打赏、带货、…

【java爬虫】将优惠券数据存入数据库排序查询

本文是在之前两篇文章的基础上进行写作的 (1条消息) 【java爬虫】使用selenium爬取优惠券_haohulala的博客-CSDN博客 (1条消息) 【java爬虫】使用selenium获取某宝联盟淘口令_haohulala的博客-CSDN博客 前两篇文章介绍了如何获取优惠券的基础信息&#xff0c;本文将获取到的…

和chatgpt学架构02-环境搭建

目录 1 安装vs code2 vs code功能介绍3 安装nodejs4 安装vue5 在vs code打开工程总结 我们在上一篇 技术选型 里咨询了chatgpt前后端的框架选择和数据库的选择。有了框架之后就需要选择合适的开发工具了&#xff0c;继续咨询一下chatgpt 我现在选型&#xff0c;前端使用vue&am…

Mac 谷歌浏览器选中查看悬浮出现的元素样式

Mac 谷歌浏览选中查看悬浮出现的元素样式 1. Mac 暂停脚本执行快捷键 command \或F8 2.以斗鱼主站下载悬浮面板为例 3. 操作步骤 &#xff08;1&#xff09;打开控制台&#xff0c;选中源代码 &#xff08;2&#xff09;鼠标选中下载&#xff0c;让面板悬浮出来 &#xf…

【GitOps系列】K8s极简实战

文章目录 示例应用介绍部署应用到k8s 如何使用命名空间隔离团队及应用环境&#xff1f;如何为业务选择最适合的工作负载类型&#xff1f;如何解决服务发现问题&#xff1f;如何迁移应用配置&#xff1f;如何将集群的业务服务暴露外网访问&#xff1f;如何保障业务资源需求和自动…

Selenium自动化之弹窗处理

1.前言 我们在使用Selenium做Web自动化测试时&#xff0c;页面经常出现弹窗&#xff0c;如果不处理后续的测试脚本就无法正常运行&#xff0c;今天我们就带大家一起来学习如何处理Web页面上的弹窗。 2.Web页面弹窗的分类 弹窗通常有3种&#xff1a;Alert类型弹框、Confirm类…

【文生图系列】stable diffusion webui 汉化(双语)教程

文章目录 安装双语插件下载json源文件设置双语 这篇博文记录于我成功安装双语插件之后&#xff0c;所以以下的示例页面均是双语。汉化教程分为三步&#xff0c;安装插件&#xff0c;JSON源文件下载和最后一步的双语设置。 安装双语插件 在扩展&#xff08;extensions&#xf…

【已解决】idea使用debug启动一直卡着不动

debug启动时一直卡着不动出现下图提示&#xff0c;但是正常启动又可以启动 翻译结果是&#xff1a;方法断点可能会大大降低调试速度。很明显&#xff0c;有断点的位置没加对或者误加断点了&#xff0c;以下是解决方法。 打开 .idea文件夹&#xff0c;找到workspace.xml文件 找…

引入Vue的方式

1.cdn引入 <html lang"en"> <head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"viewport" content"widthdevice-width, initial-scale1.0"…

配置需求分类中的科目分配

其中科目分配的内容都为灰色无法修改 结果是在科目分配里面单独维护的&#xff1a; 路径&#xff1a;销售分销-基本功能-科目分配/成本-维护成本科目分配的需求类别

【Ceph集群应用】Ceph对象存储系统之RGW接口详解

Ceph对象存储系统之RGW接口详解 1.创建Ceph对象存储系统RGW接口2. 开启httphttps,更改监听端口3. 更改监听端口4.S3接口访问测试5.实验中遇到的故障案例 接上文基于ceph-deploy部署Ceph集群详解 1.创建Ceph对象存储系统RGW接口 &#xff08;1&#xff09;对象存储概念 对象存…

广州市番禺区委领导一行莅临和鲸科技考察交流

7月18日下午&#xff0c;广州市番禺区区委常委、组织部部长、人才工作局局长唐力明&#xff0c;组织部副部长、两新工委书记罗翌洁及组织部其他相关领导一行莅临和鲸科技开展实地考察与调研&#xff0c;国投科创广州基地负责人、海创人才南方创业服务中心常务副秘书长徐斌&…

详解C#开发Android应用程序的流程

Android系统一下子铺天盖地而来&#xff0c;让人目不暇接。兴奋的同时也让部分开发人员犯难了&#xff01;要知道从熟知的Wince、Mobile开发语言C#跨越到RFID-Android的Java。可不是一朝一夕就能完成的。就好比你的乾坤大挪移已经第七层了&#xff0c;却忽然要你从易筋经从头练…

Beyond Compare 代码比较工具

一、下载 官网下载地址&#xff1a; https://www.scootersoftware.com/download.php 选择 Windows 系统&#xff0c;简体中文版本&#xff0c;点击下载。 下载完成 二、安装 步骤1&#xff1a;双击安装包 步骤2&#xff1a;进入安装向导&#xff0c;点击下一步 步骤3&a…

微信小程序事件点击跳转页面的五种方法

第一种:标签 这是最常见的一种跳转方式,相当于html里的a标签 <navigator url"/pages/main/main"></navigator>第二种:wx.navigateTo({})方法 1.前端wxml <button bindtap"getCeshi" type"primary"> 测试按钮 </button>…

php连接上mysql数据库该的配置方法

用mysql官方的管理工具workbench&#xff1a; 打开导出界面后&#xff0c;下一步&#xff0c;选择csv格式&#xff0c;导出后excel就能打开了 如果你需要在程序代码中导出&#xff0c;需要找到对应代码的excel处理库。 如php 的 phpExcel( 最新版已更名为 phpoffice/phpspread…

思维决定发展,测试人也不例外

最近特别懒&#xff0c;不想码字&#xff0c;原本写作就很差&#xff0c;更是退化严重。社招和校招面试过很多人&#xff0c;从十年前自己还很弱的时候学着面试&#xff0c;到数百次面试积累之后&#xff0c;面对候选人的时候&#xff0c;我的内心依然有些许紧张&#xff0c;非…

域内信息收集

将网络中多台计算机逻辑上组织到一起进行集中管理&#xff0c;这种区别于工作组的逻辑环境叫 做域。域是由域控制器(Domain Controller)和成员计算机组成&#xff0c;域控制器就是安装了活动 目录(Active Directory)的计算机。活动目录提供了存储网络上对象信息并使用网络使用该…