311 lines
		
	
	
		
			12 KiB
		
	
	
	
		
			C#
		
	
	
	
			
		
		
	
	
			311 lines
		
	
	
		
			12 KiB
		
	
	
	
		
			C#
		
	
	
	
| using AOP.Common.DataConversion;
 | |
| using Baidu.Aip.Face;
 | |
| using Newtonsoft.Json;
 | |
| using System;
 | |
| using System.Collections.Generic;
 | |
| using System.IO;
 | |
| using System.Linq;
 | |
| using System.Net;
 | |
| using System.Net.Http;
 | |
| using System.Text;
 | |
| using System.Threading.Tasks;
 | |
| 
 | |
| namespace SgManager.AI
 | |
| {
 | |
| 
 | |
|     public static class FaceClass
 | |
|     {
 | |
| 
 | |
| 
 | |
|         public static Baidu.Aip.Face.Face getFaceClant()
 | |
|         {
 | |
|             // 设置APPID/AK/SK
 | |
|             var APP_ID = System.Configuration.ConfigurationManager.AppSettings["APP_ID"].ToString();
 | |
|             var API_KEY = System.Configuration.ConfigurationManager.AppSettings["API_KEY"].ToString();
 | |
|             var SECRET_KEY = System.Configuration.ConfigurationManager.AppSettings["SECRET_KEY"].ToString();
 | |
|             var client = new Baidu.Aip.Face.Face(API_KEY, SECRET_KEY);
 | |
|             client.Timeout = 60000;  // 修改超时时间
 | |
|             return client;
 | |
| 
 | |
|         }
 | |
| 
 | |
| 
 | |
|         public static object SearchFileFace(String imagePath)
 | |
|         {
 | |
|             String strbaser64 = ConvertDataFormatAndImage.ImageToByte64String(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg); // 图片的base64编码
 | |
|             var imageType = "BASE64";
 | |
|             var groupIdList = "SNEC_0";
 | |
|             // 如果有可选参数
 | |
|             var options = new Dictionary<string, object>{
 | |
|             {"quality_control", "NORMAL"},
 | |
|             {"liveness_control", "NORMAL"},
 | |
|             {"max_user_num", 1}
 | |
|             };
 | |
|             // 带参数调用人脸搜索
 | |
|             object result = new object();
 | |
|             List<faceResult> frs = new List<faceResult>();
 | |
|             try
 | |
|             {
 | |
|                 result = getFaceClant().Search(strbaser64, imageType, groupIdList, options);
 | |
| 
 | |
|                 if (result != null)
 | |
|                 {
 | |
|                     var data = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(result));
 | |
|                     String error_msg = data.error_msg;
 | |
|                     String errorCode = data.error_code;
 | |
|                     if (error_msg == "SUCCESS")
 | |
|                     {
 | |
| 
 | |
|                         for (int i = 0; i < data.result.user_list.Count; i++)
 | |
|                         {
 | |
|                             faceResult fr = new faceResult();
 | |
|                             fr.user_id = data.result.user_list[i].user_id;
 | |
|                             fr.user_info = getUserName(fr.user_id);
 | |
|                             fr.errMess = error_msg;
 | |
|                             try
 | |
|                             {
 | |
|                                 string score = data.result.user_list[i].score.ToString();
 | |
|                                 fr.score = double.Parse(score);
 | |
|                             }
 | |
|                             catch
 | |
|                             {
 | |
|                                 fr.score = 0;
 | |
|                             }
 | |
|                             if (fr.score > 85)
 | |
|                                 frs.Add(fr);
 | |
| 
 | |
|                         }
 | |
|                     }
 | |
|                     else
 | |
|                     {
 | |
|                         faceResult fr = new faceResult();
 | |
|                         fr.errMess = error_msg;
 | |
|                         fr.errCode = errorCode;
 | |
|                         frs.Add(fr);
 | |
|                     }
 | |
|                 }
 | |
|             }
 | |
|             catch (Exception ex)
 | |
|             {
 | |
|                 faceResult fr = new faceResult();
 | |
|                 fr.errMess = ex.ToString();
 | |
|                 frs.Add(fr);
 | |
|             }
 | |
|             return frs;
 | |
|         }
 | |
| 
 | |
|         public static object SearchFace(String url)
 | |
|         {
 | |
|             var image = url;
 | |
|             var imageType = "URL";
 | |
|             var groupIdList = "SNEC_0";
 | |
|             // 如果有可选参数
 | |
|             var options = new Dictionary<string, object>{
 | |
|             {"quality_control", "NORMAL"},
 | |
|             {"liveness_control", "LOW"},
 | |
|             {"max_user_num", 1}
 | |
|             };
 | |
|             // 带参数调用人脸搜索
 | |
|             object result = new object();
 | |
|             try
 | |
|             {
 | |
|                 result = getFaceClant().Search(image, imageType, groupIdList, options);
 | |
|             }
 | |
|             catch (Exception ex)
 | |
|             {
 | |
|                 return null;
 | |
|             }
 | |
|             List<faceResult> frs = new List<faceResult>();
 | |
|             if (result != null)
 | |
|             {
 | |
|                 var data = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeObject(result));
 | |
|                 String error_msg = data.error_msg;
 | |
|                 if (error_msg == "SUCCESS")
 | |
|                 {
 | |
| 
 | |
|                     for (int i = 0; i < data.result.user_list.Count; i++)
 | |
|                     {
 | |
|                         faceResult fr = new faceResult();
 | |
|                         fr.user_id = data.result.user_list[i].user_id;
 | |
|                         fr.user_info = getUserName(fr.user_id);
 | |
| 
 | |
|                         try
 | |
|                         {
 | |
|                             string score = data.result.user_list[i].score.ToString();
 | |
|                             fr.score = double.Parse(score);
 | |
|                         }
 | |
|                         catch
 | |
|                         {
 | |
|                             fr.score = 0;
 | |
|                         }
 | |
|                         if (fr.score > 85)
 | |
|                         {
 | |
|                             frs.Add(fr);
 | |
|                             break;
 | |
|                         }
 | |
| 
 | |
|                     }
 | |
|                 }
 | |
|                 else return null;
 | |
|             }
 | |
|             return frs;
 | |
|         }
 | |
| 
 | |
| 
 | |
|         public static String getUserName(string id)
 | |
|         {
 | |
|             string userName = "未知用户";
 | |
|             switch (id)
 | |
|             {
 | |
| 
 | |
|                 case "A01844":
 | |
|                     userName = "张腾云";
 | |
|                     break;
 | |
|                 case "A04979":
 | |
|                     userName = "张延强";
 | |
|                     break;
 | |
|                 case "A05352":
 | |
|                     userName = "王勇C";
 | |
|                     break;
 | |
|                 case "A06539":
 | |
|                     userName = "崔璐峰";
 | |
|                     break;
 | |
|                 case "A04984":
 | |
|                     userName = "杨新民";
 | |
|                     break;
 | |
|                 case "A05303":
 | |
|                     userName = "李文娟";
 | |
|                     break;
 | |
|                 case "A04988":
 | |
|                     userName = "马明";
 | |
|                     break;
 | |
|                 case "A06926":
 | |
|                     userName = "王建峰";
 | |
|                     break;
 | |
|                 default:
 | |
|                     userName = "未知用户";
 | |
|                     break;
 | |
| 
 | |
| 
 | |
|             }
 | |
|             return userName;
 | |
| 
 | |
|         }
 | |
| 
 | |
|         // 在线活体检测
 | |
|         public static string FaceVerify(string imagePath)
 | |
|         {
 | |
|             string token = AccessToken.getAccessToken();
 | |
|             string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceverify?access_token=" + token;
 | |
|             Encoding encoding = Encoding.Default;
 | |
|             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
 | |
|             request.Method = "post";
 | |
|             request.KeepAlive = true;
 | |
|             String strbaser64 = ConvertDataFormatAndImage.ImageToByte64String(imagePath, System.Drawing.Imaging.ImageFormat.Jpeg); // 图片的base64编码
 | |
|             String str = "[{\"image\":\"" + strbaser64 + "\",\"image_type\":\"BASE64\",\"face_field\":\"quality,human\"}]";
 | |
|             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 static string add(string user_id, string user_card, string imgUrl, string token)
 | |
|         {
 | |
|             bool first = true;
 | |
|             if (string.IsNullOrEmpty(token))
 | |
|             {
 | |
|                 token = AccessToken.getAccessToken();
 | |
|                 first = false;
 | |
|             }
 | |
|             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 = "{\"image\":\"" + imgUrl + "\",\"image_type\":\"URL\",\"group_id\":\"SNEC_0\",\"user_id\":\"" + user_card + "\",\"user_info\":\"" + user_id + "\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}";
 | |
|             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);
 | |
|             var res = JsonConvert.DeserializeObject<dynamic>(result);
 | |
| 
 | |
|             if (result.Contains("Access token invalid or no longer valid") && first)
 | |
|             {
 | |
|                 token = null;
 | |
|                 add(user_id, user_card, imgUrl, token);
 | |
|             }
 | |
| 
 | |
|             if (result.Contains("face is already exist"))
 | |
|                 result = update(user_id, user_card, imgUrl, token);
 | |
|             if (res.error_code == "0")
 | |
|             {
 | |
| 
 | |
|             }
 | |
|             return result;
 | |
|         }
 | |
|         // 人脸更新
 | |
|         public static string update(string user_id, string user_card, string imgUrl, string token)
 | |
|         {
 | |
|             if (string.IsNullOrEmpty(token))
 | |
|                 token = AccessToken.getAccessToken();
 | |
|             string host = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update?access_token=" + token;
 | |
|             Encoding encoding = Encoding.Default;
 | |
|             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
 | |
|             request.Method = "post";
 | |
|             request.KeepAlive = true;
 | |
|             String str = "{\"image\":\"" + imgUrl + "\",\"image_type\":\"URL\",\"group_id\":\"SNEC_0\",\"user_id\":\"" + user_card + "\",\"user_info\":\"" + user_id + "\",\"quality_control\":\"LOW\",\"liveness_control\":\"NORMAL\"}";
 | |
|             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();
 | |
|             if (result.Contains("user is not exist"))
 | |
|                 result = add(user_id, user_card, imgUrl, token);
 | |
|             return result;
 | |
|         }
 | |
| 
 | |
| 
 | |
|     }
 | |
| 
 | |
| 
 | |
|     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 = "百度云应用的AK";
 | |
|         // 百度云中开通对应服务应用的 Secret Key
 | |
|         private static String clientSecret = "百度云应用的SK";
 | |
| 
 | |
|         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", System.Configuration.ConfigurationManager.AppSettings["API_KEY"].ToString()));
 | |
|             paraList.Add(new KeyValuePair<string, string>("client_secret", System.Configuration.ConfigurationManager.AppSettings["SECRET_KEY"].ToString()));
 | |
| 
 | |
|             HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
 | |
|             String result = response.Content.ReadAsStringAsync().Result;
 | |
|             var to = JsonConvert.DeserializeObject<dynamic>(result);
 | |
|             Console.WriteLine(result);
 | |
|             return to.access_token;
 | |
|         }
 | |
|     }
 | |
| }
 |