C#窗口调用百度云实现人脸识别。(注意代码中添加的控件以及部分传值给函数,亲测百分百可用。)

调用的dll库文件

网上都能下载到这些库文件,第一个是调用摄像头需要的,添加到引用之后,在讲这个dll拖至控件栏,使用其中的VedioSourcePlayer控件便可使用电脑自带摄像头。

代码模块

首先是连接开启电脑摄像头,拍照后保存照片到本地。
然后是调用百度云:
1.获取百度云access_token与百度云连接;
2.建立控制太应用:人脸识别;
3.人脸库的人脸注册,讲摄像头拍下保存到本地的照片上传到人脸库;
4人脸搜索、人脸对比等。

注意

百度云有针对各种语言的示例代码,需要自我完成的代码部分主要是:
1.摄像头开启,拍照保存图片到本地。
2.将百度云的返回Json格式中的某个属性值提取出来,这个是本代码里面个人觉得刚接触C#比较费时间的部分。

上代码

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Http;
using System.IO;
using System.Net;
using AForge.Video.DirectShow;
using System.Drawing.Imaging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WpfApp2
{
    public partial class 人脸识别 : Form
    {
        FilterInfoCollection videoDevices;
        VideoCaptureDevice videoSource;
        public int selectedDeviceIndex = 0;
        public 人脸识别()
        {
            InitializeComponent();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

      

        
        //获取包含access_token属性的Json格式的返回值
        public static class AccessToken
        {
            // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
            // 返回token示例
            public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";

            // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
            private static String clientId = "tFdkznWHGXy8hFgUsABqAPpM";
            // 百度云中开通对应服务应用的 Secret Key
            private static String clientSecret = "VlimF4g7dYyGyNcdbwbYiFvkpxFllkO0";

            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;
                Console.WriteLine(result);
                return result;
            }
        }

        //百度云人懒检测与属性分析,获得人脸的一些特征值
        public class FaceDetect
        {

            // 人脸检测与属性分析

            public static string detect(string oyp)
            {
                //获取json格式中的access_token属性值
                var jsonstring = AccessToken.getAccessToken();
                var jObject = JObject.Parse(jsonstring);
                string token = jObject["access_token"].ToString();

                //百度云示例代码
                string host = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + token;
                Encoding encoding = Encoding.Default;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
                request.Method = "post";
                request.KeepAlive = true;
                //保存在本地E盘
                var value = File.ReadAllBytes("E:/ppp" + oyp);

                //百度云 C#sdk文档说明:需要BASE64格式 以及我想要获取的属性:age beauty gebder
                string imgData64 = Convert.ToBase64String(value);
                String str = "{\"image\":\"" + imgData64 + "\",\"image_type\":\"BASE64\",\"face_field\":\"age,beauty,gender\"}";

                //百度云示例代码 不需变更
                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();
                Console.WriteLine("人脸检测与属性分析:");
                Console.WriteLine(result);

                //获取人脸检测与属性分析json格式中的 beauty属性值
                JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                string val = jo["result"]["face_list"].ToString();
                JArray ja = (JArray)JsonConvert.DeserializeObject(val);
                Double st = Convert.ToDouble(ja[0]["beauty"].ToString());
                return st.ToString();//返回字符串格式给TextBox控件
            }
        }
        //百度云人脸注册,上传本地照片到人脸库
        public class FaceAdd
        {
            // 人脸注册
            public static string add(string qdb, string name)
            {
                var jsonstring = AccessToken.getAccessToken();
                var jObject = JObject.Parse(jsonstring);
                string token = jObject["access_token"].ToString();
                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;
                var value = File.ReadAllBytes("E:/ppp" + qdb);
                string imgData64 = Convert.ToBase64String(value);
                String str = "{\"image\":\"" + imgData64 + "\",\"image_type\":\"BASE64\",\"group_id\":\"922513\",\"user_id\":\"" + name + "\"}";
                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();
                Console.WriteLine("人脸注册:");
                Console.WriteLine(result);
                return result;
            }
        }

        //百度云人脸搜索,获得相似度进行判断
        public class FaceSearch
        {
           
            // 人脸搜索
            public static Double search(string ch)
            {
                var jsonstring = AccessToken.getAccessToken();
                var jObject = JObject.Parse(jsonstring);
                string token = jObject["access_token"].ToString();
                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;
                var value = File.ReadAllBytes("E:/ppp" + ch);
                string imgData64 = Convert.ToBase64String(value);
                String str = "{\"image\":\"" + imgData64 + "\",\"image_type\":\"BASE64\",\"group_id_list\":\"922513\"}";
                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();
                Console.WriteLine("人脸搜索:");
                //获取人脸搜索返回的json格式中的score属性值(相似度)
                JObject jo = (JObject)JsonConvert.DeserializeObject(result);
                string val = jo["result"]["user_list"].ToString();
                JArray ja = (JArray)JsonConvert.DeserializeObject(val);
                Double st = Convert.ToDouble(ja[0]["score"].ToString());
                
                return st;

            }
        }
        //连接/开启摄像头
        private void button3_Click(object sender, EventArgs e)
        {
            videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
            selectedDeviceIndex = 0;
            videoSource = new VideoCaptureDevice(videoDevices[selectedDeviceIndex].MonikerString);//连接摄像头。
            videoSource.VideoResolution = videoSource.VideoCapabilities[selectedDeviceIndex];
            videoSourcePlayer2.VideoSource = videoSource;
            // set NewFrame event handler
            videoSourcePlayer2.Start();
        }
        //保存照片到本地
        private void button4_Click(object sender, EventArgs e)
        {
            if (videoSource == null)
                return;
            Bitmap bitmap = videoSourcePlayer2.GetCurrentVideoFrame();
            string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ff") + ".jpg";
            //textBox3控件里面输出加入人脸库的用户名字
            string name = textBox3.Text;
            bitmap.Save(@"E:\ppp" + fileName, ImageFormat.Jpeg);
            bitmap.Dispose();
            //将路径传给人脸检测函数,同时将返回值给textBox2:靓丽度:beauty
            textBox2.Text = FaceDetect.detect(fileName);
            //将变量值传给搜索函数,注册函数
            FaceSearch.search(fileName);
            FaceAdd.add(fileName, name);
            Double compare = FaceSearch.search(fileName); 
	
           /* //这部分可删除,这是在WPF中开启这个winform窗口
            if (compare > 90.0)
            {
            
                Window2 win1 = new Window2();
                win1.Show();
                this.Close();
                MessageBox.Show("亲爱的管理员,您已成功登陆");
            }
            else
            {
                MessageBox.Show("人脸库无存档,您没有权限登陆");
            }*/

        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void 人脸识别_Load(object sender, EventArgs e)
        {

        }
    }
}

代码demo下载地址

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值