C# Winform調(diào)用百度接口實(shí)現(xiàn)人臉識(shí)別教程(附源碼)
百度是個(gè)好東西,這篇調(diào)用了百度的接口(當(dāng)然大牛也可以自己寫),人臉檢測(cè)技術(shù),所以使用的前提是有網(wǎng)的情況下。當(dāng)然大家也可以去參考百度的文檔。

話不多說(shuō),我們開始:
第一步,在百度創(chuàng)建你的人臉識(shí)別應(yīng)用
打開百度AI開放平臺(tái)鏈接: 點(diǎn)擊跳轉(zhuǎn)百度人臉檢測(cè)鏈接,創(chuàng)建新應(yīng)用

創(chuàng)建成功成功之后。進(jìn)行第二步
第二步,使用API Key和Secret Key,獲取 AssetToken
平臺(tái)會(huì)分配給你相關(guān)憑證,拿到API Key和Secret Key,獲取 AssetToken

接下來(lái)我們創(chuàng)建一個(gè)AccessToken類,來(lái)獲取我們的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í)間 設(shè)置緩存
// 返回token示例
public static string TOKEN = "24.ddb44b9a5e904f9201ffc1999daa7670.2592000.1578837249.282335-18002137";
// 百度云中開通對(duì)應(yīng)服務(wù)應(yīng)用的 API Key 建議開通應(yīng)用的時(shí)候多選服務(wù)
private static string clientId = "這里是你的API Key";
// 百度云中開通對(duì)應(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,保存拍到的圖片信息,保存到百度云端中,用于以后掃描秒人臉做對(duì)比。
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;
}
}
第四步,定義人臉注冊(cè)和搜索類FaceOperate
定義人臉注冊(cè)和搜索類FaceOperate,里面定義兩個(gè)方法分別為,注冊(cè)人臉?lè)椒ê退阉魅四樂(lè)椒ā?/p>
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>
/// 注冊(cè)人臉
/// </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控件,對(duì)人臉進(jìn)行拍攝
現(xiàn)在我們是沒(méi)有這個(gè)控件的,所以我們要先導(dǎo)包,點(diǎn)擊我們的工具選項(xiàng)卡,選擇NuGet包管理器,管理解決方案的NuGet程序包,安裝一下的包:

然后我們就能看到videoSourcePlayer控件,把它繪制在窗體上就好了。

第五步,調(diào)用攝像頭拍攝注冊(cè)人臉

然后我們就可以寫控制攝像頭的語(yǔ)句以及拍攝之后注冊(cè)處理的方法了:
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);
//實(shí)例化攝像頭
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);
//實(shí)例化FaceInfo對(duì)象
FaceInfo faceInfo = new FaceInfo();
faceInfo.Image = imagStr;
faceInfo.ImageType = "BASE64";
faceInfo.GroupId = "admin";
faceInfo.UserId = Guid.NewGuid().ToString().Replace('-', '_');//生成一個(gè)隨機(jī)的UserId 可以固定為用戶的主鍵
faceInfo.UserInfo = "";
using (FaceOperate faceOperate = new FaceOperate())
{
faceOperate.token = tocken;
//調(diào)用注冊(cè)方法注冊(cè)人臉
var msg = faceOperate.Add(faceInfo);
if (msg.ErroCode == 0)
{
MessageBox.Show("添加成功");
//關(guān)閉攝像頭
videoSourcePlayer1.Stop();
}
}
}
}
}
我們?cè)谔砑尤四樦罂梢缘桨俣戎荒茉频娜四槑?kù)中查看一下添加是否成功。

如果添加成功,那么恭喜,我們就可以進(jìn)行人臉識(shí)別了。
第六步,拍攝之后對(duì)比查詢?nèi)四樧R(shí)別
然后我們就可以寫控制攝像頭的語(yǔ)句以及拍攝之后搜索處理的方法了:
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("人員不存在,錯(cuò)誤提示"+e, "系統(tǒng)提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (dialog == DialogResult.OK)
{
this.Close();
}
}
}
}
private void videoSourcePlayer1_Click(object sender, EventArgs e)
{
NewMethod();
}
}
}
寫到這我們就結(jié)束了,人臉識(shí)別的注冊(cè)和搜索功能就已經(jīng)都實(shí)現(xiàn)完畢了,接下來(lái)我們還可以在百度智能云的監(jiān)控報(bào)報(bào)表中查看調(diào)用次數(shù)
查看監(jiān)控報(bào)表

到此這篇關(guān)于C# Winform調(diào)用百度接口實(shí)現(xiàn)人臉識(shí)別教程(附源碼)的文章就介紹到這了,更多相關(guān)C# 百度接口人臉識(shí)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用WPF實(shí)現(xiàn)Windows屏保的制作
屏保程序的本質(zhì)上就是一個(gè)Win32?窗口應(yīng)用程序。本文將利用WPF實(shí)現(xiàn)Windows屏保的制作,文中的示例代碼簡(jiǎn)潔易懂,對(duì)我們學(xué)習(xí)WPF有一定幫助,感興趣的可以了解一下2022-07-07
C#開發(fā)Windows UWP系列之布局面板RelativePanel
這篇文章介紹了C#開發(fā)Windows UWP系列之布局面板RelativePanel,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06
C# 從Excel讀取數(shù)據(jù)向SQL server寫入
這篇文章主要介紹了C# 從Excel讀取數(shù)據(jù)向SQL server寫入的方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
基于C#實(shí)現(xiàn)簡(jiǎn)單的音樂(lè)播放器
這篇文章主要介紹了如何基于C#實(shí)現(xiàn)簡(jiǎn)單的音樂(lè)播放器,考慮到需求中的界面友好和跨版本兼容性,我們可以選擇選擇Windows Forms作為開發(fā)平臺(tái),Windows Forms提供了一個(gè)簡(jiǎn)單而強(qiáng)大的方法來(lái)創(chuàng)建桌面應(yīng)用程序,文中通過(guò)代碼示例給大家講解的非常詳細(xì),需要的朋友可以參考下2024-05-05
C#使用AForge實(shí)現(xiàn)調(diào)用攝像頭的示例詳解
AForge是一個(gè)專門為開發(fā)者和研究者基于C#框架設(shè)計(jì)的,這個(gè)框架提供了不同的類庫(kù)和關(guān)于類庫(kù)的資源,本文為大家介紹了C#使用AForge實(shí)現(xiàn)調(diào)用攝像頭的相關(guān)教程,需要的可以了解下2023-11-11
C# SynchronizationContext以及Send和Post使用解讀
這篇文章主要介紹了C# SynchronizationContext以及Send和Post使用解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05

