当前位置:   article > 正文

基于winfrom通过调用百度AI的人脸识别,实现人脸检测、人脸对比、人脸登录_winform人脸识别登录

winform人脸识别登录

概述

本项目代码已经开源,可通过文章末尾的链接进行查看。注意的是,本项目的代码涉及到隐私内容(如AK、SK)均作脱敏处理,部分代码因个人原因不做展示,请读者自行脑补。

获取并调用百度人脸识别功能的 API Key 、Secret Key

获取

这里跳过在百度ai开放平台进行登录、领取免费额度(或购买额度)的操作。
在这里插入图片描述
我们在这里百度智能云 - 管理中心创建应用(记得勾选需要的功能)后,就可以在如图所示的界面中找到自己的API Key、Secret Key,记住这两个key都很重要,不要泄露出去,以避免不必要的损失。

调用

这里我们直接根据技术文档中的示例代码进行AccessToken获取,AccessToken的获取示例代码如下:


using System;
using System.Collections.Generic;
using System.Net.Http;

namespace com.baidu.ai
{
    public static class AccessToken

    {
        // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
        // 返回token示例
        public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";

        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static String clientId = "百度云应用的AK";
        // 百度云中开通对应服务应用的 Secret Key
        private static String clientSecret = "百度云应用的SK";

        public static String getAccessToken() {
            String authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
            paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
            paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            String result = response.Content.ReadAsStringAsync().Result;
            Console.WriteLine(result);
            return result;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

在这里直接把API Key、Secret Key修改为自己的key就行了。需要注意的是,这里返回的result值是一个json,里面包含了不止AccessToken的信息,需要我们自行写一个函数进行AccessToken值提取。

人脸库的创建和应用

创建

在这里插入图片描述
在可视化人脸库这里,我们可以很轻松地创建自己的人脸库,并且可以在这个人脸库中手动添加照片。但是这样做太麻烦了,我们会在后面的内容中直接调用函数来进行人脸注册。

应用

这里直接套用百度的示例代码即可:


using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;

namespace com.baidu.ai
{
    public class FaceSearch
    {
        // 人脸搜索
        public static string faceSearch()
        {
            string token = "[调用鉴权接口获取的token]";
            string host = "https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            String str = "{"image":"027d8308a2ec665acb1bdf63e513bcb9","image_type":"FACE_TOKEN","group_id_list":"group_repeat,group_233","quality_control":"LOW","liveness_control":"NORMAL"}";
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            Console.WriteLine("人脸搜索:");
            Console.WriteLine(result);
            return result;
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

在这里我们需要修改的是string token = "[调用鉴权接口获取的token]";,将token换成我们前文提到的函数;String str = "{"image":"……","image_type":"……","group_id_list":"……","quality_control":"……","liveness_control":"……"}";这里面的值修改成你想要的属性,具体有哪些属性可以在技术文档中看到。

具体代码编写

在这里先把我的成品ui图放出来:
在这里插入图片描述
这里我们将按照该ui界面展示的功能进行逐一功能描述。

搜寻设备中可用摄像头

private void search_device()
        {
            vedioDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            if (vedioDevices != null && vedioDevices.Count > 0)
            {
                comboBox1.Items.Clear();
                foreach (FilterInfo device in vedioDevices)
                {
                    comboBox1.Items.Add(device.Name);
                }
                comboBox1.SelectedIndex = 0;
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

这里我们选用FilterCategory来收集设备上可用视频设备。

开启摄像头

private void CameraConn()
        {
            if (comboBox1.Items.Count<=0)
            {
                return;
            }
            videoSource = new VideoCaptureDevice(vedioDevices[comboBox1.SelectedIndex].MonikerString);
            videoSource.VideoResolution = videoSource.VideoCapabilities[0];

            videoSource.DesiredFrameRate = 1;

            videoSourcePlayer1.VideoSource = videoSource;
            videoSourcePlayer1.Start();
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

这里我们通过设置组件videoSource来进行摄像头的调用。

摄像头拍照

private void button9_Click(object sender, EventArgs e)
        {
            if (!videoSourcePlayer1.IsRunning)
            {
                MessageBox.Show("摄像头未启动");
                return;
            }
            try
            {
                if (videoSourcePlayer1.IsRunning)
                {
                    BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                                    videoSourcePlayer1.GetCurrentVideoFrame().GetHbitmap(),
                                    IntPtr.Zero,
                                     Int32Rect.Empty,
                                    BitmapSizeOptions.FromEmptyOptions());
                    PngBitmapEncoder pE = new PngBitmapEncoder();
                    pE.Frames.Add(BitmapFrame.Create(bitmapSource));
                    string picName = GetImagePath() + "\\" + DateTime.Now.ToFileTime() + ".jpg";
                    // 若存在文件则删除旧文件
                    if (File.Exists(picName))
                    {
                        File.Delete(picName);
                    }
                    // 保存文件
                    using (Stream stream = File.Create(picName))
                    {
                        pE.Save(stream);
                        selectedImage1Path = picName;
                        MessageBox.Show("照片保存成功,保存在:\n"+ picName);
                    }

                    pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
                    pictureBox2.Load(picName);
                }
            }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

这段代码实现了通过摄像头捕获当前视频帧,并将其保存为图像文件。通过使用videoSourcePlayer1控件获取视频帧,并使用PngBitmapEncoder进行编码和保存,实现了将摄像头捕获的图像保存到指定路径并显示在pictureBox2控件上的功能。

在图片框中插入图片

string selectedImage1Path = "";
string selectedImage2Path = "";
private void pictureBox2_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog1.Filter = "选择图片|*.*";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    selectedImage1Path = openFileDialog1.FileName;
                }
                pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
                pictureBox2.Load(selectedImage1Path);
            }
            catch (Exception ex)
            {
                MessageBox.Show("错误:" + ex.Message);
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

这段代码实现了通过点击图片框来选择并显示图片文件的功能。通过使用openFileDialog1对话框来选择文件,并将选择的图片文件路径存储在变量中,然后使用pictureBox2.Load方法加载该图片文件并在图片框上显示。这样,用户就可以通过点击图片框来选择要显示的图片文件。

“获取Token”——测试accesstoken是否被正常获取

        private void button1_Click(object sender, EventArgs e)
        {
            string token = getAccessToken();
            if (!string.IsNullOrEmpty(token))
            {
                MessageBox.Show($"获取AccessToken成功,access_Token为:\n{token}");
            }
            return;
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

人脸检测、人脸对比、人脸登录

参考百度人脸识别技术文档

本地图片转base64

// 转换base64编码
        public static string ConvertJpgToBase64(string imagePath)
        {
            try
            {
                using (FileStream fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read))
                {
                    byte[] imageBytes = new byte[fileStream.Length];
                    fileStream.Read(imageBytes, 0, (int)fileStream.Length);
                    return Convert.ToBase64String(imageBytes);
                }
            }
            catch (Exception ex)
            {
                // 处理异常,例如文件不存在或无法读取
                Console.WriteLine($"转换错误: {ex.Message}");
                return null;
            }
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

这个方法的作用是将指定的JPEG图像文件转换为Base64编码的字符串表示形式。使用FileStream读取图像文件的内容,并将其转换为字节数组。然后,使用Convert.ToBase64String方法将字节数组转换为Base64编码的字符串。这对于在需要将图像数据以文本形式传输或存储的场景非常有用。

成果展示

照片均来源于网络,侵删。

人脸检测

在这里插入图片描述

人脸对比

在这里插入图片描述

人脸登录(人脸搜索)

在这里插入图片描述

总结

本项目展示了如何使用百度智能云的人脸识别功能,涉及API Key和Secret Key的获取与调用。项目通过示例代码详细介绍了AccessToken的获取过程,并演示了人脸库的创建与应用。代码实现了摄像头的连接、拍照功能、图片加载等操作,结合百度智能云的API实现了人脸检测、人脸对比和人脸登录等功能。本文提供的代码示例和技术文档链接将有助于读者更好地理解和应用人脸识别技术。具体实现细节和完整代码请参考本文提供的链接。

参考资料

完整源码:

链接

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/893979
推荐阅读
  

闽ICP备14008679号