C# Winform调用百度接口实现人脸识别教程(附源码)
百度是个好东西,这篇调用了百度的接口(当然大牛也可以自己写),人脸检测技术,所以使用的前提是有网的情况下。当然大家也可以去参考百度的文档。
话不多说,我们开始:
第一步,在百度创建你的人脸识别应用
打开百度AI开放平台链接: 点击跳转百度人脸检测链接,创建新应用
创建成功成功之后。进行第二步
第二步,使用API Key和Secret Key,获取 AssetToken
平台会分配给你相关凭证,拿到API Key和Secret Key,获取 AssetToken
接下来我们创建一个AccessToken类,来获取我们的AccessToken
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace AegeanHotel_management_system { class AccessToken { // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存 // 返回token示例 public static string TOKEN = "24.ddb44b9a5e904f9201ffc1999daa7670.2592000.1578837249.282335-18002137"; // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务 private static string clientId = "这里是你的API Key"; // 百度云中开通对应服务应用的 Secret Key private static string clientSecret = "这里是你的Secret Key"; 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; return result; } } }
第三步,封装图片信息类Face,保存图像信息
封装图片信息类Face,保存拍到的图片信息,保存到百度云端中,用于以后扫描秒人脸做对比。
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AegeanHotel_management_system { [Serializable] class Face { [JsonProperty(PropertyName = "image")] public string Image { get; set; } [JsonProperty(PropertyName = "image_type")] public string ImageType { get; set; } [JsonProperty(PropertyName = "group_id_list")] public string GroupIdList { get; set; } [JsonProperty(PropertyName = "quality_control")] public string QualityControl { get; set; } = "NONE"; [JsonProperty(PropertyName = "liveness_control")] public string LivenessControl { get; set; } = "NONE"; [JsonProperty(PropertyName = "user_id")] public string UserId { get; set; } [JsonProperty(PropertyName = "max_user_num")] public int MaxUserNum { get; set; } = 1; } }
第四步,定义人脸注册和搜索类FaceOperate
定义人脸注册和搜索类FaceOperate,里面定义两个方法分别为,注册人脸方法和搜索人脸方法。
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace AegeanHotel_management_system { class FaceOperate : IDisposable { public string token { get; set; } /// <summary> /// 注册人脸 /// </summary> /// <param name="face"></param> /// <returns></returns> public FaceMsg Add(FaceInfo face) { string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=" + token; Encoding encoding = Encoding.Default; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host); request.Method = "post"; request.KeepAlive = true; String str = JsonConvert.SerializeObject(face); 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(); FaceMsg msg = JsonConvert.DeserializeObject<FaceMsg>(result); return msg; } /// <summary> /// 搜索人脸 /// </summary> /// <param name="face"></param> /// <returns></returns> public MatchMsg FaceSearch(Face face) { 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 = JsonConvert.SerializeObject(face); ; 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(); MatchMsg msg = JsonConvert.DeserializeObject<MatchMsg>(result); return msg; } public void Dispose() { } } }
在把类定义完成之后,我们就可以绘制我们的摄像头了videoSourcePlayer
第五步,绘制videoSourcePlayer控件,对人脸进行拍摄
现在我们是没有这个控件的,所以我们要先导包,点击我们的工具选项卡,选择NuGet包管理器,管理解决方案的NuGet程序包,安装一下的包:
然后我们就能看到videoSourcePlayer控件,把它绘制在窗体上就好了。
第五步,调用摄像头拍摄注册人脸
然后我们就可以写控制摄像头的语句以及拍摄之后注册处理的方法了:
using AForge.Video.DirectShow; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AegeanHotel_management_system { public partial class FrmFacePeople : Form { string tocken = ""; public FrmFacePeople() { InitializeComponent(); Tocken tk = JsonConvert.DeserializeObject<Tocken>(AccessToken.getAccessToken()); this.tocken = tk.AccessToken; } private FilterInfoCollection videoDevices; private VideoCaptureDevice videoDevice; private void FrmFacePeople_Load(object sender, EventArgs e) { //获取摄像头 videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); //实例化摄像头 videoDevice = new VideoCaptureDevice(videoDevices[0].MonikerString); //将摄像头视频播放在控件中 videoSourcePlayer1.VideoSource = videoDevice; //开启摄像头 videoSourcePlayer1.Start(); } private void FrmFacePeople_FormClosing(object sender, FormClosingEventArgs e) { videoSourcePlayer1.Stop(); } private void button1_Click(object sender, EventArgs e) { //拍照 Bitmap img = videoSourcePlayer1.GetCurrentVideoFrame(); //图片转Base64 string imagStr = ImagHelper.ImgToBase64String(img); //实例化FaceInfo对象 FaceInfo faceInfo = new FaceInfo(); faceInfo.Image = imagStr; faceInfo.ImageType = "BASE64"; faceInfo.GroupId = "admin"; faceInfo.UserId = Guid.NewGuid().ToString().Replace('-', '_');//生成一个随机的UserId 可以固定为用户的主键 faceInfo.UserInfo = ""; using (FaceOperate faceOperate = new FaceOperate()) { faceOperate.token = tocken; //调用注册方法注册人脸 var msg = faceOperate.Add(faceInfo); if (msg.ErroCode == 0) { MessageBox.Show("添加成功"); //关闭摄像头 videoSourcePlayer1.Stop(); } } } } }
我们在添加人脸之后可以到百度只能云的人脸库中查看一下添加是否成功。
如果添加成功,那么恭喜,我们就可以进行人脸识别了。
第六步,拍摄之后对比查询人脸识别
然后我们就可以写控制摄像头的语句以及拍摄之后搜索处理的方法了:
using AForge.Video.DirectShow; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AegeanHotel_management_system { public partial class FrmFaceDemo : Form { string tocken = ""; FrmLogin login; public FrmFaceDemo(FrmLogin login) { this.login = login; InitializeComponent(); //获取Token并反序列化 Tocken tk = JsonConvert.DeserializeObject<Tocken>(AccessToken.getAccessToken()); this.tocken = tk.AccessToken; } private FilterInfoCollection videoDevices; private VideoCaptureDevice videoDevice; private void FrmFaceDemo_Load(object sender, EventArgs e) { videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); videoDevice = new VideoCaptureDevice(videoDevices[0].MonikerString); videoSourcePlayer1.VideoSource = videoDevice; //开启摄像头 videoSourcePlayer1.Start(); } private void NewMethod() { //获取图片 拍照 Bitmap img = videoSourcePlayer1.GetCurrentVideoFrame(); //关闭相机 videoSourcePlayer1.Stop(); //图片转Base64 string imagStr = ImagHelper.ImgToBase64String(img); Face faceInfo = new Face(); faceInfo.Image = imagStr; faceInfo.ImageType = "BASE64"; faceInfo.GroupIdList = "admin"; this.Hide(); using (FaceOperate faceOperate = new FaceOperate()) { try { faceOperate.token = tocken; //调用查找方法 var msg = faceOperate.FaceSearch(faceInfo); foreach (var item in msg.Result.UserList) { //置信度大于90 认为是本人 if (item.Score > 90) { DialogResult dialog = MessageBox.Show("登陆成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); //this.label1.Text = item.UserId; if (dialog == DialogResult.OK) { FrmShouYe shouye = new FrmShouYe(); shouye.Show(); login.Hide(); this.Close(); } return; } else { DialogResult dialog = MessageBox.Show("人员不存在", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); if (dialog == DialogResult.OK) { this.Close(); } } } } catch (Exception e) { DialogResult dialog = MessageBox.Show("人员不存在,错误提示"+e, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information); if (dialog == DialogResult.OK) { this.Close(); } } } } private void videoSourcePlayer1_Click(object sender, EventArgs e) { NewMethod(); } } }
写到这我们就结束了,人脸识别的注册和搜索功能就已经都实现完毕了,接下来我们还可以在百度智能云的监控报报表中查看调用次数
查看监控报表
到此这篇关于C# Winform调用百度接口实现人脸识别教程(附源码)的文章就介绍到这了,更多相关C# 百度接口人脸识别内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!
相关文章
- 我们在使用C#做项目的时候,基本上都需要制作登录界面,那么今天我们就来一步步看看,如果简单的实现登录界面呢,本文给出2个例子,由简入难,希望大家能够喜欢。...2020-06-25
- 这篇文章主要介绍了C# 字段和属性的的相关资料,文中示例代码非常详细,供大家参考和学习,感兴趣的朋友可以了解下...2020-11-03
- 这篇文章主要介绍了C#中截取字符串的的基本方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-11-03
- 本文给大家分享C#连接SQL数据库和查询数据功能的操作技巧,本文通过图文并茂的形式给大家介绍的非常详细,需要的朋友参考下吧...2021-05-17
- 这篇文章主要介绍了C#实现简单的Http请求的方法,以实例形式较为详细的分析了C#实现Http请求的具体方法,需要的朋友可以参考下...2020-06-25
- 本文主要介绍了C#中new的几种用法,具有很好的参考价值,下面跟着小编一起来看下吧...2020-06-25
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
这篇文章主要介绍了使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25- 这篇文章主要介绍了C#开发Windows窗体应用程序的简单操作步骤,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-04-12
- 这篇文章主要介绍了C#从数据库读取图片并保存的方法,帮助大家更好的理解和使用c#,感兴趣的朋友可以了解下...2021-01-16
- 最近做一个小项目不可避免的需要前端脚本与后台进行交互。由于是在asp.net中实现,故问题演化成asp.net中jiavascript与后台c#如何进行交互。...2020-06-25
- 这篇文章主要用实例讲解C#递归算法的概念以及用法,文中代码非常详细,帮助大家更好的参考和学习,感兴趣的朋友可以了解下...2020-06-25
- 本文通过例子,讲述了C++调用C#的DLL程序的方法,作出了以下总结,下面就让我们一起来学习吧。...2020-06-25
- 轻松学习C#的基础入门,了解C#最基本的知识点,C#是一种简洁的,类型安全的一种完全面向对象的开发语言,是Microsoft专门基于.NET Framework平台开发的而量身定做的高级程序设计语言,需要的朋友可以参考下...2020-06-25
- 本文主要介绍了C#变量命名规则小结,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-09-09
- 这篇文章主要介绍了c#中(&&,||)与(&,|)的区别详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
- 本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
- 这篇文章主要介绍了C#绘制曲线图的方法,以完整实例形式较为详细的分析了C#进行曲线绘制的具体步骤与相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
- 这篇文章主要介绍了c#自带缓存使用方法,包括获取数据缓存、设置数据缓存、移除指定数据缓存等方法,需要的朋友可以参考下...2020-06-25
- 下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
- 这篇文章主要介绍了C#中list用法,结合实例形式分析了C#中list排序、运算、转换等常见操作技巧,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25