歡迎您光臨本站 註冊首頁

C# Winform呼叫百度介面實現人臉識別教程

←手機掃碼閱讀     f2h0b53ohn @ 2020-05-12 , reply:0

百度是個好東西,這篇呼叫了百度的介面(當然大牛也可以自己寫),人臉檢測技術,所以使用的前提是有網的情況下。當然大家也可以去參考百度的文件。
話不多說,我們開始:
第一步,在百度建立你的人臉識別應用
開啟百度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

> paraList = new List<KeyValuePair>(); paraList.Add(new KeyValuePair("grant_type", "client_credentials")); paraList.Add(new KeyValuePair("client_id", clientId)); paraList.Add(new KeyValuePair("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; } ////// 註冊人臉 /////////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(result); return msg; } ////// 搜尋人臉 /////////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(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(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(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(); } } }
寫到這我們就結束了,人臉識別的註冊和搜尋功能就已經都實現完畢了,接下來我們還可以在百度智慧雲的監控報報表中檢視呼叫次數


[f2h0b53ohn ] C# Winform呼叫百度介面實現人臉識別教程已經有246次圍觀

http://coctec.com/docs/program/show-post-234029.html