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# 百度接口人脸识别内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: Unity Shader实现裁切效果