最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C# Winform調(diào)用百度接口實現(xiàn)人臉識別教程(附源碼)

 更新時間:2020年05月11日 09:26:35   作者:Even-LittleMonkey  
這篇文章主要介紹了C# Winform調(diào)用百度接口實現(xiàn)人臉識別教程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

百度是個好東西,這篇調(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# 打開電子郵件軟件的具體方法

    C# 打開電子郵件軟件的具體方法

    這篇文章介紹了C# 打開電子郵件軟件的具體方法,有需要的朋友可以參考一下
    2013-11-11
  • C#?PictureBox控件方法參數(shù)及圖片刪除重命名上傳詳解

    C#?PictureBox控件方法參數(shù)及圖片刪除重命名上傳詳解

    這篇文章主要為大家介紹了C#?PictureBox控件方法參數(shù)及圖片刪除重命名上傳示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-08-08
  • Unity實現(xiàn)批量Build打包詳解

    Unity實現(xiàn)批量Build打包詳解

    一般來講如果項目是PC或Android、IOS端不會有批量Build打包這樣的需求,但如果項目是WebGL端可能會遇到這樣的需求。本文主要為大家介紹Unity中如何實現(xiàn)Build批量打包的,需要的朋友可以參考一下
    2021-12-12
  • C#中常見的系統(tǒng)內(nèi)置委托用法詳解

    C#中常見的系統(tǒng)內(nèi)置委托用法詳解

    這篇文章主要介紹了C#中常見的系統(tǒng)內(nèi)置委托用法,主要包括了Action類的委托、Func類的委托、Predicate<T>委托、Comparison<T>委托等,需要的朋友可以參考下
    2014-09-09
  • webBrowser代理設(shè)置c#代碼

    webBrowser代理設(shè)置c#代碼

    本文將介紹C# 為webBrowser設(shè)置代理實現(xiàn)代碼,需要了解的朋友可以參考下
    2012-11-11
  • C# IP地址與整數(shù)之間轉(zhuǎn)換的具體方法

    C# IP地址與整數(shù)之間轉(zhuǎn)換的具體方法

    這篇文章介紹了C# IP地址與整數(shù)之間轉(zhuǎn)換的具體方法,有需要的朋友可以參考一下
    2013-10-10
  • 關(guān)于C# Math 處理奇進(jìn)偶不進(jìn)的實現(xiàn)代碼

    關(guān)于C# Math 處理奇進(jìn)偶不進(jìn)的實現(xiàn)代碼

    下面小編就為大家?guī)硪黄P(guān)于C# Math 處理奇進(jìn)偶不進(jìn)的實現(xiàn)代碼。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-05-05
  • C#集合類用法實例代碼詳解

    C#集合類用法實例代碼詳解

    本文通過實例代碼給大家介紹了C#集合類用法的相關(guān)知識,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2017-10-10
  • 大白話講解C# 中的委托

    大白話講解C# 中的委托

    這篇文章主要介紹了C# 中的委托的相關(guān)資料,幫助初學(xué)者更好的理解和使用c#,感興趣的朋友可以了解下
    2020-11-11
  • C# 格式化JSON的兩種實現(xiàn)方式

    C# 格式化JSON的兩種實現(xiàn)方式

    本文主要介紹了C# 格式化JSON的兩種實現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05

最新評論

宜宾市| 英吉沙县| 赤城县| 克拉玛依市| 桃园县| 枣强县| 阿坝县| 岑溪市| 抚顺市| 盐池县| 宿州市| 伊宁县| 丰城市| 文登市| 道孚县| 沁源县| 固始县| 彰武县| 太仆寺旗| 安顺市| 历史| 陇川县| 延庆县| 衡东县| 通辽市| 古交市| 台山市| 阳城县| 咸宁市| 武义县| 盖州市| 措勤县| 微山县| 普陀区| 巴塘县| 内乡县| 兰州市| 休宁县| 达孜县| 九龙城区| 泰宁县|