C# Winform調(diào)用百度接口實現(xiàn)人臉識別教程(附源碼)
百度是個好東西,這篇調(diào)用了百度的接口(當(dāng)然大牛也可以自己寫),人臉檢測技術(shù),所以使用的前提是有網(wǎng)的情況下。當(dāng)然大家也可以去參考百度的文檔。
話不多說,我們開始:
第一步,在百度創(chuàng)建你的人臉識別應(yīng)用
打開百度AI開放平臺鏈接: 點(diǎn)擊跳轉(zhuǎn)百度人臉檢測鏈接,創(chuàng)建新應(yīng)用
創(chuàng)建成功成功之后。進(jìn)行第二步
第二步,使用API Key和Secret Key,獲取 AssetToken
平臺會分配給你相關(guān)憑證,拿到API Key和Secret Key,獲取 AssetToken
接下來我們創(chuàng)建一個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 { // 調(diào)用getAccessToken()獲取的 access_token建議根據(jù)expires_in 時間 設(shè)置緩存 // 返回token示例 public static string TOKEN = "24.ddb44b9a5e904f9201ffc1999daa7670.2592000.1578837249.282335-18002137"; // 百度云中開通對應(yīng)服務(wù)應(yīng)用的 API Key 建議開通應(yīng)用的時候多選服務(wù) private static string clientId = "這里是你的API Key"; // 百度云中開通對應(yīng)服務(wù)應(yīng)用的 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控件,對人臉進(jìn)行拍攝
現(xiàn)在我們是沒有這個控件的,所以我們要先導(dǎo)包,點(diǎn)擊我們的工具選項卡,選擇NuGet包管理器,管理解決方案的NuGet程序包,安裝一下的包:
然后我們就能看到videoSourcePlayer控件,把它繪制在窗體上就好了。
第五步,調(diào)用攝像頭拍攝注冊人臉
然后我們就可以寫控制攝像頭的語句以及拍攝之后注冊處理的方法了:
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(); //圖片轉(zhuǎn)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('-', '_');//生成一個隨機(jī)的UserId 可以固定為用戶的主鍵 faceInfo.UserInfo = ""; using (FaceOperate faceOperate = new FaceOperate()) { faceOperate.token = tocken; //調(diào)用注冊方法注冊人臉 var msg = faceOperate.Add(faceInfo); if (msg.ErroCode == 0) { MessageBox.Show("添加成功"); //關(guān)閉攝像頭 videoSourcePlayer1.Stop(); } } } } }
我們在添加人臉之后可以到百度只能云的人臉庫中查看一下添加是否成功。
如果添加成功,那么恭喜,我們就可以進(jìn)行人臉識別了。
第六步,拍攝之后對比查詢?nèi)四樧R別
然后我們就可以寫控制攝像頭的語句以及拍攝之后搜索處理的方法了:
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(); //關(guān)閉相機(jī) videoSourcePlayer1.Stop(); //圖片轉(zhuǎn)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; //調(diào)用查找方法 var msg = faceOperate.FaceSearch(faceInfo); foreach (var item in msg.Result.UserList) { //置信度大于90 認(rèn)為是本人 if (item.Score > 90) { DialogResult dialog = MessageBox.Show("登陸成功", "系統(tǒng)提示", 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("人員不存在", "系統(tǒng)提示", MessageBoxButtons.OK, MessageBoxIcon.Information); if (dialog == DialogResult.OK) { this.Close(); } } } } catch (Exception e) { DialogResult dialog = MessageBox.Show("人員不存在,錯誤提示"+e, "系統(tǒng)提示", MessageBoxButtons.OK, MessageBoxIcon.Information); if (dialog == DialogResult.OK) { this.Close(); } } } } private void videoSourcePlayer1_Click(object sender, EventArgs e) { NewMethod(); } } }
寫到這我們就結(jié)束了,人臉識別的注冊和搜索功能就已經(jīng)都實現(xiàn)完畢了,接下來我們還可以在百度智能云的監(jiān)控報報表中查看調(diào)用次數(shù)
查看監(jiān)控報表
到此這篇關(guān)于C# Winform調(diào)用百度接口實現(xiàn)人臉識別教程(附源碼)的文章就介紹到這了,更多相關(guān)C# 百度接口人臉識別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#開發(fā)Windows UWP系列之布局面板RelativePanel
這篇文章介紹了C#開發(fā)Windows UWP系列之布局面板RelativePanel,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06C# 從Excel讀取數(shù)據(jù)向SQL server寫入
這篇文章主要介紹了C# 從Excel讀取數(shù)據(jù)向SQL server寫入的方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03C#使用AForge實現(xiàn)調(diào)用攝像頭的示例詳解
AForge是一個專門為開發(fā)者和研究者基于C#框架設(shè)計的,這個框架提供了不同的類庫和關(guān)于類庫的資源,本文為大家介紹了C#使用AForge實現(xiàn)調(diào)用攝像頭的相關(guān)教程,需要的可以了解下2023-11-11C# SynchronizationContext以及Send和Post使用解讀
這篇文章主要介紹了C# SynchronizationContext以及Send和Post使用解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05