C# Winform调用百度接口实现人脸识别教程(附源码

编辑: admin 分类: c#语言 发布时间: 2022-01-18 来源:互联网

百度是个好东西,这篇调用了百度的接口(当然大牛也可以自己写),人脸检测技术,所以使用的前提是有网的情况下。当然大家也可以去参考百度的文档。


话不多说,我们开始:

第一步,在百度创建你的人脸识别应用

打开百度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 可以固定为用户的主键
     【本文由:http://www.yidunidc.com/mgzq.html复制请保留原URL】 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#  百度接口人脸识别内容请搜索海外IDC网以前的文章或继续浏览下面的相关文章希望大家以后多多支持海外IDC网!