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

2020-05-11 13:58: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;
  }
}