当前位置:首页 » 《我的小黑屋》 » 正文

使用百度ai人脸识别,实现人脸检测、人脸对比

26 人参与  2024年10月04日 18:00  分类 : 《我的小黑屋》  评论

点击全文阅读


目录

一、前期准备

1、注册“百度AI开放平台”

2、安装Nuget程序包

二、代码设计

1、页面设计

2、前期配置

3、人脸检测

4、选择人脸图

5、人脸对比

三、总结


一、前期准备

1、注册“百度AI开放平台”

搜索进入“百度AI开放平台”,点击“开放能力”-“人脸与人体”-“人脸识别云服务”

人脸识别_人脸识别_准确率99.99%_免费试用-百度AI开放平台 (baidu.com)

点击“立即使用”

点击“免费尝鲜”领取人脸识别接口,点击“创建应用”创建新的应用

勾选需要用到的接口,点击“0元领取”

可以在“可视化人脸库”添加人脸

在“应用列表”可以看到自己的APPID、API Key、Secret Key

2、安装Nuget程序包

在VS2022中安装以下Nuget程序包

二、代码设计

1、页面设计

添加控件:button、label、textbox、panel、videosourceplayer

2、前期配置

根据百度AI人脸识别“创建应用”处所给内容将API填入

        private string APP_ID = "换成你的APP_ID";        private string API_KEY = "换成你的API_KEY";        private string SECRET_KEY = "换成你的SECRET_KEY";        private Face client = null;        private bool IsStart = false;        private FaceLocation location = null;        private FilterInfoCollection videoDevices = null;        private VideoCaptureDevice videoSource;

将一个Image对象转换为其Base64编码的字符串形式。

Base64编码常用于在文本格式中嵌入二进制数据,例如在网络编程中,当需要将图像、文件或其他二进制数据作为文本传输时。

        public string ConvertImageToBase64(Image file)        {            using (MemoryStream memoryStream = new MemoryStream())            {                file.Save(memoryStream, file.RawFormat);                byte[] imageBytes = memoryStream.ToArray();                return Convert.ToBase64String(imageBytes);            }        }

定义一个名为 ReadImg 的方法,该方法接受一个字符串参数 img指向图像文件的路径。

该方法的功能是读取该图像文件的所有字节,并将其转换为 Base64 编码的字符串。

        public string ReadImg(string img)        {            return Convert.ToBase64String(File.ReadAllBytes(img));        }

连接并打开摄像头

        private void CameraConn()        {            if (comboBox1.Items.Count<=0)            {                MessageBox.Show("请插入视频设备");                return;            }            videoSource = new VideoCaptureDevice(videoDevices[comboBox1.SelectedIndex].MonikerString);            videoSource.DesiredFrameSize = new System.Drawing.Size(320, 240);            videoSource.DesiredFrameRate = 1;                        videoSourcePlayer1.VideoSource = videoSource;            videoSourcePlayer1.Start();        }

3、人脸检测

(1)参数验证:首先,验证传入的 image 对象是否为非空的 Bitmap 类型。这是为了确保后续处理的数据是有效的图像数据。

(2)图像转换:如果图像验证通过,将 Bitmap 图像转换为 Base64 编码的字符串 image1。这是因为很多网络服务(如人脸检测API)通常要求图像数据以Base64编码的字符串形式发送。

(3)设置检测选项:代码创建了一个包含检测选项的字典 options。这些选项指定了检测API的行为,例如返回的人脸数量上限(max_face_num)和需要检测的人脸属性(face_fields)。

(4)调用人脸检测API:使用设置好的选项和Base64编码的图像字符串,代码调用了 client.Detect 方法(这个方法可能是对某个外部API的封装)。这个API执行人脸检测,并返回检测结果。

(5)解析检测结果:检测结果(假设是JSON格式的字符串)被反序列化为 FaceDetectInfo 类型的对象 detect。这个对象包含了检测到的人脸信息,如年龄、位置、质量等。

(6)处理检测结果:如果检测到人脸,代码会读取并显示第一个检测到的人脸的年龄信息。同时,它还会检查人脸的质量属性,如模糊度、完整性、光照和遮挡情况,并根据预设的阈值判断是否存在问题。

public void Detect(object image){    if (image!=null &&  image is Bitmap)    {        try        {            Bitmap img = (Bitmap)image;            var imgByte = Bitmap2Byte(img);            Image im =img ;            string image1 = ConvertImageToBase64(im);            string imageType = "BASE64";            if (imgByte != null)            {                // 如果有可选参数                var options = new Dictionary<string, object>{                    {"max_face_num", 2},                    {"face_fields", "age,qualities,beauty"}                };                var result = client.Detect(image1, imageType,options);                FaceDetectInfo detect = JsonHelper.DeserializeObject<FaceDetectInfo>(result.ToString());                if (detect!=null && detect.result_num>0)                {                    ageText.Text = detect.result[0].age.TryToString();                    this.location = detect.result[0].location;                    StringBuilder sb = new StringBuilder();                    if (detect.result[0].qualities != null)                    {                        if (detect.result[0].qualities.blur >= 0.7)                        {                            sb.AppendLine("人脸过于模糊");                        }                        if (detect.result[0].qualities.completeness >= 0.4)                        {                            sb.AppendLine("人脸不完整");                        }                        if (detect.result[0].qualities.illumination <= 40)                        {                            sb.AppendLine("灯光光线质量不好");                        }                        if (detect.result[0].qualities.occlusion!=null)                        {                            if (detect.result[0].qualities.occlusion.left_cheek>=0.8)                            {                                sb.AppendLine("左脸颊不清晰");                            }                            if (detect.result[0].qualities.occlusion.left_eye >= 0.6)                            {                                sb.AppendLine("左眼不清晰");                            }                            if (detect.result[0].qualities.occlusion.mouth >= 0.7)                            {                                sb.AppendLine("嘴巴不清晰");                            }                            if (detect.result[0].qualities.occlusion.nose >= 0.7)                            {                                sb.AppendLine("鼻子不清晰");                            }                            if (detect.result[0].qualities.occlusion.right_cheek >= 0.8)                            {                                sb.AppendLine("右脸颊不清晰");                            }                            if (detect.result[0].qualities.occlusion.right_eye >= 0.6)                            {                                sb.AppendLine("右眼不清晰");                            }                            if (detect.result[0].qualities.occlusion.chin >= 0.6)                            {                                sb.AppendLine("下巴不清晰");                            }                            if (detect.result[0].pitch>=20)                            {                                sb.AppendLine("俯视角度太大");                            }                            if (detect.result[0].roll>=20)                            {                                sb.AppendLine("脸部应该放正");                            }                            if (detect.result[0].yaw>=20)                            {                                sb.AppendLine("脸部应该放正点");                            }                        }                                            }                    if (detect.result[0].location.height<=100 || detect.result[0].location.height<=100)                    {                        sb.AppendLine("人脸部分过小");                    }                    textBox4.Text = sb.ToString();                    if (textBox4.Text.IsNull())                    {                        textBox4.Text = "OK";                    }                }            }        }        catch (Exception ex)        {            ClassLoger.Error("Form1.image", ex);        }    }    }

运行结果

4、选择人脸图

允许用户通过点击按钮(button3)打开一个文件选择对话框,选择一个文件,并将所选文件的完整路径显示在文本框中。

        private void button3_Click(object sender, EventArgs e)        {            OpenFileDialog dialog = new OpenFileDialog();            dialog.InitialDirectory = "D:\\";            dialog.Filter = "所有文件|*.*";            dialog.RestoreDirectory = true;            dialog.FilterIndex = 2;            if (dialog.ShowDialog() == DialogResult.OK)            {                if (string.IsNullOrEmpty(textBox2.Text))                {                    textBox2.Text = dialog.FileName;                }                else                {                    textBox3.Text = dialog.FileName;                }            }        }

5、人脸对比

(1)验证输入:

首先,检查textBox2和textBox3是否都包含了有效的文本。这两个文本框可能分别用于输入两张待比对的人脸图片的路径。如果任何一个文本框为空(即用户没有输入图片路径),则显示一个消息框提示用户“请选择要对比的人脸图片”,并立即退出该方法,不进行后续操作。

(2)读取图片并转换为Base64编码:

ReadImg用于读取图片文件并将其转换为Base64编码的字符串。从textBox2和textBox3中获取图片路径,并分别调用ReadImg方法将图片转换为Base64编码的字符串。

(3)构建请求数据:

使用JArray和JObject构建了一个包含两张人脸图片信息的JSON数组faces。对于每张图片,都包含了一个JSON对象,该对象描述了图片的Base64编码、图片类型(这里固定为"BASE64")、人脸类型(这里固定为"LIVE",表示活体检测)、质量控制(这里设置为"LOW")和活体检测控制(这里设置为"NONE",表示不进行活体检测)。

(4)调用人脸比对API:

使用构建好的faces数组作为参数,调用client.Match方法。client.Match方法执行人脸比对操作,并返回比对结果。

(5)处理并显示结果:

将client.Match方法的返回结果转换为字符串,并显示在textBox1中。

        private void button2_Click(object sender, EventArgs e)        {            if (string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text))            {                MessageBox.Show("请选择要对比的人脸图片");                return;            }            try            {                string path1=textBox2.Text;                string path2=textBox3.Text;                                var faces = new JArray                {                    new JObject                    {                        {"image", ReadImg(path1)},                        {"image_type", "BASE64"},                        {"face_type", "LIVE"},                        {"quality_control", "LOW"},                        {"liveness_control", "NONE"},                    },                    new JObject                    {                        {"image", ReadImg(path2)},                        {"image_type", "BASE64"},                        {"face_type", "LIVE"},                        {"quality_control", "LOW"},                        {"liveness_control", "NONE"},                    }                 };                                // 带参数调用人脸比对                var result = client.Match(faces);                textBox1.Text = result.ToString();            }            catch (Exception ex)            { }        }

运行结果

三、总结

本次实验,成功调用百度ai人脸识别,实现了人脸检测和两张人脸图片的比对功能。可以通过界面选择待比对的图片,程序能够自动读取图片、调用人脸识别API进行比对,并在界面上显示比对结果。最后,我意识到人脸比对技术在日常实习工作技术领域中具有广泛的应用前景。无论是身份验证、安防监控还是社交娱乐等领域,都需要用到人脸比对技术。通过本次实验,我不仅掌握了相关的编程技能,还了解了人脸比对技术的原理和应用场景,这将为我在实习工作中更好地应用该技术提供有力的支持。


点击全文阅读


本文链接:http://zhangshiyu.com/post/167783.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1