赞
踩
注意:
1. apikey 和 apisecret 换成你自己的(这个东西怎么获得网上一堆)
2. 新建下面两个脚本,将facedetect.cs 脚本挂载到任意对象上 , base64太长了,你更换成你需要的图片的base64即可
3.这是人脸检测和人脸融合的两个方法
- using System;
- using System.Collections.Generic;
- using System.Net.Http;
-
- namespace com.baidu.ai
- {
- public static class AccessToken
-
- {
- // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
- // 返回token示例
- public static String TOKEN = "24.216acc9390da75b7a11e338d13d97144.2592000.1562208663.282335-16428924";
-
- // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
- private static String clientId = " "; // 这里写自己的id
- // 百度云中开通对应服务应用的 Secret Key
- private static String clientSecret = " "; // 这里写自己的 Secret
-
-
- 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;
- }
- }
- }
- using System;
- using System.IO;
- using System.Net;
- using System.Text;
- using System.Web;
- using UnityEngine;
- using System.Drawing;
- using UnityEngine.UI;
-
- namespace com.baidu.ai
- {
- public class FaceDetect: MonoBehaviour
- {
- public RawImage raw;
- public Image image;
-
- String UrlPath01;
- String UrlPath02;
- string token;
- string ReceiveBase64Str;
- string Base64Image01;
- string Base64Image02;
- public void Start()
- {
- token = AccessToken.getAccessToken();
- string[] tokens = token.Split(new string[] { "\"access_token\":\"", "\",\"scope" }, StringSplitOptions.RemoveEmptyEntries);
- token = tokens[1];
- UrlPath01 = Application.streamingAssetsPath + @"/2.jpg";
- UrlPath02 = Application.streamingAssetsPath + @"/TemplateImage.png";
- Base64Image01 = ImgToBase64String(UrlPath01);
- Base64Image02 = ImgToBase64String(UrlPath02);
- //Debug.Log(token);
- detect();
- //facemerge();
- }
- //人脸检测与属性分析
- public string detect()
- {
-
- Debug.Log("token " + token);
- 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;
- //String str = "{\"image\":\"" + Base64Image01 + "\",\"image_type\":\"BASE64\",\"face_field\":\"faceshape,facetype\"}";
- String str = "{\"image\":\"" + Base64Image01 + "\",\"image_type\":\"BASE64\",\"face_field\":\"age,beauty,expression,face_shape,gender,glasses,landmark,landmark150,race,quality,eye_status,emotion,face_type\"}";
- 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();
- Debug.Log("人脸检测与属性分析:");
- Debug.Log(result);
- return result;
- }
-
- // 人脸融合
- public string facemerge()
- {
- string host = "https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=" + token;
- Encoding encoding = Encoding.Default;
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
- request.Method = "post";
- request.KeepAlive = true;
- String str = "{\"image_template\":{\"image\":\"" + Base64Image02 +"\",\"image_type\":\"BASE64\",\"quality_control\":\"NONE\"},\"image_target\":{\"image\":\""+ Base64Image01 +"\",\"image_type\":\"BASE64\",\"quality_control\":\"NONE\"}}";
- 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();
- Debug.Log(result);
- string[] ArrayStr = result.Split(new string[] { "merge_image\":\"", "\"}}" }, StringSplitOptions.RemoveEmptyEntries);
- ReceiveBase64Str = ArrayStr[1];
- ReceiveBase64Str = ReceiveBase64Str.Replace("\\","");
-
-
- raw.texture = Base64ToTexter2d(ReceiveBase64Str); // 图片显示 Base64图片
- Debug.Log("人脸融合:");
- return ReceiveBase64Str;
- }
-
- public void Save(string sb,string name)
- {
- //写文件 文件名为save.text
- //这里的FileMode.create是创建这个文件,如果文件名存在则覆盖重新创建
- FileStream fs = new FileStream(Application.dataPath + "/" + name+".txt", FileMode.Create);
- //存储时时二进制,所以这里需要把我们的字符串转成二进制
- byte[] bytes = new UTF8Encoding().GetBytes(sb.ToString());
- fs.Write(bytes, 0, bytes.Length);
- //每次读取文件后都要记得关闭文件
- fs.Close();
- }
-
- /// <summary>
- /// 图片转换成base64编码文本
- /// </summary>
- public string ImgToBase64String(string path)
- {
-
- FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
- byte[] buffer = new byte[fs.Length];
- fs.Read(buffer, 0, (int)fs.Length);
- string base64String = Convert.ToBase64String(buffer);
- // Debug.Log("获取当前图片base64为---" + base64String);
- return base64String;
- }
-
- /// <summary>
- /// base64编码文本转换成Texture
- /// </summary>
-
- private Texture2D Base64ToTexter2d(string Base64STR)
- {
- Texture2D pic = new Texture2D(200, 200);
- byte[] data = System.Convert.FromBase64String(Base64STR);
- //File.WriteAllBytes(Application.dataPath + "/BuildImage/Base64ToSaveImage.png", data);
- pic.LoadImage(data);
- return pic;
- }
-
- /// <summary>
- /// base64编码文本转换成图片
- /// </summary>
-
- public void Base64ToImg(Image imgComponent,string str)
- {
- string base64 = str;
- byte[] bytes = Convert.FromBase64String(base64);
- Texture2D tex2D = new Texture2D(100, 100);
- tex2D.LoadImage(bytes);
- Sprite s = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), new Vector2(0.5f, 0.5f));
- imgComponent.sprite = s;
- Resources.UnloadUnusedAssets();
- }
-
-
-
- }
- }
结果如下:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。