【C#】使用百度AI进行人脸检测和人脸比对(windows程序设计作业三)

一、作业内容

        使用百度AI进行人脸检测和人脸比对。

        人脸检测:用户点击button1来选择一张图片文件,然后将该图片转换为Base64编码的字符串,并使用百度AI(client)来检测图片中的人脸,并将结果显示在textBox3中(包括年龄、美丽度等数据)。

        人脸对比:用户点击button2来选择两张图片文件(两张图片的文件路径放在textBox1textBox2),然后将该图片转换为Base64编码的字符串,并使用百度AI(client)来对两张图片进行人脸比对,并将结果显示在textBox3中。

二、程序包

安装使用了visual studio 中的Baidu.AI程序包。

用户界面如下:

 

 三、代码介绍

        1、声明API密钥:API_KEY 和 SECRET_KEY 是两个私有字符串变量,它们被用来存储从BaiduAI开放平台获得的API密钥和秘密密钥。这些密钥是必需的,以便应用程序可以安全地访问和使用Baidu AI Face API。

private string API_KEY = "1nhS4AcrLFffxqDKB73bb1U7";
private string SECRET_KEY = "rtnRFv5RcE0dMxBWqmL6PX3LYwVAdETW";

        2、声明了一个Face类型的变量client,并将其初始化为null。这个Face类是对Baidu AI Face API的一个封装或客户端库的一部分,用于简化与该API的交互。 然后,使用之前声明的API_KEYSECRET_KEY来创建一个新的Face客户端实例,并将其赋值给client变量,这样就可以使用这个client变量来调用Baidu AI Face API的各种方法。

private Face client = null;
client = new Face(API_KEY, SECRET_KEY);

        3、ConvertImageToBase64方法接受一个Image对象作为参数,并使用MemoryStream将其转换为Base64编码的字符串。

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

         4、创建了一个新的OpenFileDialog对象实例,该对象通常用于显示一个文件选择对话框,让用户从文件选择对话框的初始目录为D:\图片中选择一个文件。

OpenFileDialog dialog = new OpenFileDialog();

dialog.InitialDirectory = "D:\\图片";
dialog.Filter = "所有文件|*.*";
dialog.RestoreDirectory = true;
dialog.FilterIndex = 1;

         5、定义了两个字典,optionsoptions1,它们包含了一些可选参数。

// 如果有可选参数
var options = new Dictionary<string, object>{
    //{"max_face_num", 2},
    {"face_field", "age,beauty"},
    {"face_fields", "age,qualities,beauty"}
};

var options1 = new Dictionary<string, object>{
    {"face_field", "age"},
    {"max_face_num", 2},
    {"face_type", "LIVE"},
    {"liveness_control", "LOW"}
};

        6、使用clientDetect方法来进行人脸检测。这个方法接收Base64编码的图片、图片类型以及可选参数作为输入,并将检测结果存储显示在textBox3中。

var result = client.Detect(image, imageType, options);
textBox3.Text = result.ToString();

        7、文件选择:button2_Click 方法,用户点击button2时,会打开一个文件选择对话框,初始目录为"D:",对话框允许用户选择所有类型的文件(所有文件|*.*),如果用户选择了一个文件并点击了“打开”按钮,程序会检查textBox1是否为空。如果textBox1为空,则将所选文件的路径显示在textBox1中;否则,将所选文件的路径显示在textBox2中。

private void button2_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(textBox1.Text))
        {
            textBox1.Text = dialog.FileName;
        }
        else
        {
            textBox2.Text = dialog.FileName;
        }
    }
}

         8、定义了一个名为 ReadImg 的公共方法,它接受一个字符串参数 im给(图像文件)。该方法读取该文件的内容,将其转换为字节数组,然后使用 Convert.ToBase64String 方法将字节数组转换为 Base64 编码的字符串。该方法返回这个 Base64 编码的字符串。

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

        9、获取文本框中的路径存放在path1path2中,使用之前定义的ReadImg方法(从给定的文件路径读取图片并转换为Base64字符串)来读取path1path2中的图片,并将它们转换为Base64编码的字符串。使用JArrayJObject来构建一个JSON数组faces。使用clientMatch方法来进行人脸比对,并将结果显示在textBox3中。

string path1 = textBox1.Text;
string path2 = textBox2.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);
textBox3.Text = result.ToString();

四、代码实现

        首先,运行代码,如图:

        点击"人脸检测",选择进行人脸检测的图片文件:

        成功检测案例:

        不能检测成功案例: 

        点击"选择人脸图" ,选择两张人脸图片,然后,点击"人脸对比":

五、小结和其他功能

        在本次实验中,学习使用百度AI进行人脸检测和人脸比对的相关代码知识。其中还包括其他功能知识:1、连接电脑的视频输入设备,显示到控件videoSourcePlayer1中,并且可以对其进行拍照,2、人脸注册功能,3、人脸登录功能。通过本次代码学习,我们可以实现百度ai人脸识别功能,它可以应用到多个地方,比如每天刷脸入校。

六、完整代码

using System;
using System.Collections.Generic;
using Baidu.Aip.Face;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using System.IO;

namespace WindowsFormsApp作业3
{
    public partial class Form1 : Form
    {
        private string API_KEY = "1nhS4AcrLFffxqDKB73bb1U7";
        private string SECRET_KEY = "rtnRFv5RcE0dMxBWqmL6PX3LYwVAdETW";
        private Face client = null;
        public Form1()
        {
            InitializeComponent();
            client = new Face(API_KEY, SECRET_KEY);
        }

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

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();

            dialog.InitialDirectory = "D:\\图片";
            dialog.Filter = "所有文件|*.*";
            dialog.RestoreDirectory = true;
            dialog.FilterIndex = 1;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string filename = dialog.FileName;
                try
                {

                    Image im = Image.FromFile(filename);
                    var image = ConvertImageToBase64(im);
                    string imageType = "BASE64";


                    // 如果有可选参数
                    var options = new Dictionary<string, object>{
                        //{"max_face_num", 2},
                        {"face_field", "age,beauty"},
                        {"face_fields", "age,qualities,beauty"}
                    };

                    var options1 = new Dictionary<string, object>{
                        {"face_field", "age"},
                        {"max_face_num", 2},
                        {"face_type", "LIVE"},
                        {"liveness_control", "LOW"}
                    };

                    var result = client.Detect(image, imageType, options);

                    textBox3.Text = result.ToString();

                    //FaceDetectInfo detect = JsonHelper.DeserializeObject<FaceDetectInfo>(result.ToString());

                }
                catch (Exception ex)
                { MessageBox.Show(ex.Message); }
            }
        }
       
        private void button2_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(textBox1.Text))
                {
                    textBox1.Text = dialog.FileName;
                }
                else
                {
                    textBox2.Text = dialog.FileName;
                }
            }
        }
        public string ReadImg(string img)
        {
            return Convert.ToBase64String(File.ReadAllBytes(img));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("请选择要对比的人脸图片");
                return;
            }
            try
            {
                string path1 = textBox1.Text;
                string path2 = textBox2.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);
                textBox3.Text = result.ToString();
            }
            catch (Exception ex)
            { }
        }
    }
}

 

  • 22
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值