C ා WinForm calling Baidu interface to realize face recognition tutorial (with source code)

Time:2020-10-11

Baidu is a good thing, this article calls Baidu’s interface (of course, Daniel can also write by himself), face detection technology, so the premise of using is to have a network. Of course, you can also refer to Baidu’s documents.

Without much to say, we began:

The first step is to create your face recognition application in Baidu

Open Baidu AI open platform link: Click to jump to Baidu face detection link to create a new application

After successful creation. Proceed to the second step

Step 2: use API key and secret key to obtain assettoken

The platform will assign you the relevant credentials, get the API key and secret key, and get the assettoken

Next, we create an accesstoken class to get our 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
  {
    //Access obtained by calling getaccesstoken()_ Token suggests that the_ In time setting cache
    //Return token example
    public static string TOKEN = "24.ddb44b9a5e904f9201ffc1999daa7670.2592000.1578837249.282335-18002137";

    //Baidu cloud opens the API key of the corresponding service application. It is recommended to select multiple services when opening the application
    Private static string ClientID: "here is your API key";
    //Baidu cloud opens secret key of corresponding service application
    Private static string clientsecret: "here is your 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;
    }
  }
}

The third step is to encapsulate the image information class face and save the image information

Encapsulate the image information class face, save the captured image information, and save it to Baidu cloud for face comparison after scanning seconds.


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;
  }
}

The fourth step is to define the face registration and search class faceoperate

Define the face registration and search class faceoperate, which defines two methods, namely, face registration method and face search method.

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>
    ///Registered face
    /// </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>
    ///Search for faces
    /// </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()
    {

    }
  }
}

After defining the class, we can draw our camera, videosourceplayer

The fifth step is to draw the video source player control to shoot the face

For now, we do not need to select the management package of get Nu, so we need to select the management package of get nu

Then we can see the video source player control and just draw it on the form.

Step 5: call the camera to shoot the registered face

Then we can write the statement to control the camera and how to register after shooting:

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)
    {
      //Get the camera
      videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
      //Instantiation camera
      videoDevice = new VideoCaptureDevice(videoDevices[0].MonikerString);
      //Play the camera video in the control
      videoSourcePlayer1.VideoSource = videoDevice;
      //Turn on the camera
      videoSourcePlayer1.Start();
    }

    private void FrmFacePeople_FormClosing(object sender, FormClosingEventArgs e)
    {
      videoSourcePlayer1.Stop();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      //Take photos
      Bitmap img = videoSourcePlayer1.GetCurrentVideoFrame();
      //Picture to Base64
      string imagStr = ImagHelper.ImgToBase64String(img);
      //Instantiate faceinfo object
      FaceInfo faceInfo = new FaceInfo();
      faceInfo.Image = imagStr;
      faceInfo.ImageType = "BASE64";
      faceInfo.GroupId = "admin";
      faceInfo.UserId  = Guid.NewGuid ().ToString().Replace('-', '_ '; // generates a random userid, which can be fixed as the user's primary key
      faceInfo.UserInfo = "";
      using (FaceOperate faceOperate = new FaceOperate())
      {
        faceOperate.token = tocken;
        //Call registration method to register face
        var msg = faceOperate.Add(faceInfo);
        if (msg.ErroCode == 0)
        {
          MessageBox.Show ("added successfully");
          //Turn off the camera
          videoSourcePlayer1.Stop();
        }
      }
    }
  }
}

After adding face, we can check whether the addition is successful or not in Baidu can only cloud’s face database.

If the addition is successful, Congratulations, we can carry out face recognition.

The sixth step is to compare and query face recognition after shooting

Then we can write the statement that controls the camera and how to search after shooting:

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();
      //Get token and deserialize
      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;
      //Turn on the camera
      videoSourcePlayer1.Start();
    }
    private void NewMethod()
    {
      //Take pictures
      Bitmap img = videoSourcePlayer1.GetCurrentVideoFrame();
      //Turn off the camera
      videoSourcePlayer1.Stop();
      //Picture to 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;
          //Call the lookup method
          var msg = faceOperate.FaceSearch(faceInfo);
            
          foreach (var item in msg.Result.UserList)
          {
            //If the confidence level is greater than 90, it is considered that it is me
            if (item.Score > 90)
            {
              DialogResult dialog =  MessageBox.Show (login successful, system prompt), 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 ("personnel does not exist", "system prompt", MessageBoxButtons.OK , MessageBoxIcon.Information );
              if (dialog == DialogResult.OK)
              {
                this.Close();
              }
            }
          }
        }
        catch (Exception e)
        {
          DialogResult dialog =  MessageBox.Show ("personnel does not exist, error prompt" + e, "system prompt"), MessageBoxButtons.OK , MessageBoxIcon.Information );
          if (dialog == DialogResult.OK)
          {
            this.Close();
          }
        }
        
      }
    }

    private void videoSourcePlayer1_Click(object sender, EventArgs e)
    {
      NewMethod();
    }
  }
}

When we finish writing, we will finish the registration and search function of face recognition. Next, we can check the number of calls in the report of Baidu Intelligent Cloud monitoring report.

View Monitoring Report

This article about C ා WinForm call Baidu interface to achieve face recognition tutorial (with source code) article introduced here, more relevant C ා Baidu interface face recognition content, please search the previous articles of developpaer or continue to browse the relevant articles below, I hope you can support more developeppaer in the future!