服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C# Winform调用百度接口实现人脸识别教程(附源码)

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

2022-09-07 14:41Even-LittleMonkey C#

这篇文章主要介绍了C# Winform调用百度接口实现人脸识别教程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

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

话不多说,我们开始:

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

打开百度AI开放平台链接: 点击跳转百度人脸检测链接,创建新应用

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

创建成功成功之后。进行第二步

第二步,使用api key和secret key,获取 assettoken

平台会分配给你相关凭证,拿到api key和secret key,获取 assettoken

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

接下来我们创建一个accesstoken类,来获取我们的accesstoken

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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,保存拍到的图片信息,保存到百度云端中,用于以后扫描秒人脸做对比。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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,里面定义两个方法分别为,注册人脸方法和搜索人脸方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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程序包,安装一下的包:

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

然后我们就能看到videosourceplayer控件,把它绘制在窗体上就好了。

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

第五步,调用摄像头拍摄注册人脸

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

然后我们就可以写控制摄像头的语句以及拍摄之后注册处理的方法了:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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 可以固定为用户的主键
      faceinfo.userinfo = "";
      using (faceoperate faceoperate = new faceoperate())
      {
        faceoperate.token = tocken;
        //调用注册方法注册人脸
        var msg = faceoperate.add(faceinfo);
        if (msg.errocode == 0)
        {
          messagebox.show("添加成功");
          //关闭摄像头
          videosourceplayer1.stop();
        }
      }
    }
  }
}

我们在添加人脸之后可以到百度只能云的人脸库中查看一下添加是否成功。

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

如果添加成功,那么恭喜,我们就可以进行人脸识别了。

第六步,拍摄之后对比查询人脸识别

然后我们就可以写控制摄像头的语句以及拍摄之后搜索处理的方法了:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
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# winform调用百度接口实现人脸识别教程(附源码)的文章就介绍到这了,更多相关c#  百度接口人脸识别内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/Houoy/article/details/106043069

延伸 · 阅读

精彩推荐
  • C#C#使用winform简单导出Excel的方法

    C#使用winform简单导出Excel的方法

    这篇文章主要介绍了C#使用winform简单导出Excel的方法,结合实例形式分析了WinForm操作Excel文件的写入导出等相关技巧,需要的朋友可以参考下...

    雨竹10672021-11-26
  • C#C#知识整理

    C#知识整理

    本文主要介绍了C#的相关知识。具有很好的参考价值,下面跟着小编一起来看下吧...

    键盘上青春11272021-12-22
  • C#C#通过KD树进行距离最近点的查找

    C#通过KD树进行距离最近点的查找

    这篇文章主要为大家详细介绍了C#通过KD树进行距离最近点的查找,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    帆帆帆3752022-01-22
  • C#c#动态类型,及动态对象的创建,合并2个对象,map实例

    c#动态类型,及动态对象的创建,合并2个对象,map实例

    下面小编就为大家带来一篇c#动态类型,及动态对象的创建,合并2个对象,map实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编...

    C#教程网9462021-12-24
  • C#详解C#中的泛型以及编程中使用泛型的优点

    详解C#中的泛型以及编程中使用泛型的优点

    这篇文章主要介绍了详解C#中的泛型以及编程中使用泛型的优点,对泛型的支持时C#语言中的重要特性,需要的朋友可以参考下...

    C#教程网4462021-11-11
  • C#C#实现Nginx平滑加权轮询算法

    C#实现Nginx平滑加权轮询算法

    这篇文章主要为大家详细介绍了C#实现Nginx平滑加权轮询算法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Gangle3592022-02-27
  • C#C# 中实现ftp 图片上传功能(多快好省)

    C# 中实现ftp 图片上传功能(多快好省)

    这篇文章主要介绍了C# 中实现ftp 图片上传功能(多快好省),需要的朋友可以参考下...

    潇十一郎4352022-01-10
  • C#c#实现windows远程桌面连接程序代码

    c#实现windows远程桌面连接程序代码

    本篇文章主要介绍了c#实现windows远程桌面连接程序代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    冰不化8792022-01-05