当前位置:   article > 正文

Unity 百度AI 人脸检测 人脸融合_unity 调用百度人脸融合

unity 调用百度人脸融合

注意:

1. apikey 和 apisecret 换成你自己的(这个东西怎么获得网上一堆)

2.  新建下面两个脚本,将facedetect.cs 脚本挂载到任意对象上 , base64太长了,你更换成你需要的图片的base64即可

3.这是人脸检测和人脸融合的两个方法 

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. namespace com.baidu.ai
  5. {
  6. public static class AccessToken
  7. {
  8. // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
  9. // 返回token示例
  10. public static String TOKEN = "24.216acc9390da75b7a11e338d13d97144.2592000.1562208663.282335-16428924";
  11. // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
  12. private static String clientId = " "; // 这里写自己的id
  13. // 百度云中开通对应服务应用的 Secret Key
  14. private static String clientSecret = " "; // 这里写自己的 Secret
  15. public static String getAccessToken()
  16. {
  17. String authHost = "https://aip.baidubce.com/oauth/2.0/token";
  18. HttpClient client = new HttpClient();
  19. List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
  20. paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
  21. paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
  22. paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
  23. HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
  24. String result = response.Content.ReadAsStringAsync().Result;
  25. Console.WriteLine(result);
  26. return result;
  27. }
  28. }
  29. }
  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. using System.Web;
  6. using UnityEngine;
  7. using System.Drawing;
  8. using UnityEngine.UI;
  9. namespace com.baidu.ai
  10. {
  11. public class FaceDetect: MonoBehaviour
  12. {
  13. public RawImage raw;
  14. public Image image;
  15. String UrlPath01;
  16. String UrlPath02;
  17. string token;
  18. string ReceiveBase64Str;
  19. string Base64Image01;
  20. string Base64Image02;
  21. public void Start()
  22. {
  23. token = AccessToken.getAccessToken();
  24. string[] tokens = token.Split(new string[] { "\"access_token\":\"", "\",\"scope" }, StringSplitOptions.RemoveEmptyEntries);
  25. token = tokens[1];
  26. UrlPath01 = Application.streamingAssetsPath + @"/2.jpg";
  27. UrlPath02 = Application.streamingAssetsPath + @"/TemplateImage.png";
  28. Base64Image01 = ImgToBase64String(UrlPath01);
  29. Base64Image02 = ImgToBase64String(UrlPath02);
  30. //Debug.Log(token);
  31. detect();
  32. //facemerge();
  33. }
  34. //人脸检测与属性分析
  35. public string detect()
  36. {
  37. Debug.Log("token " + token);
  38. string host = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=" + token;
  39. Encoding encoding = Encoding.Default;
  40. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
  41. request.Method = "post";
  42. request.KeepAlive = true;
  43. //String str = "{\"image\":\"" + Base64Image01 + "\",\"image_type\":\"BASE64\",\"face_field\":\"faceshape,facetype\"}";
  44. 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\"}";
  45. byte[] buffer = encoding.GetBytes(str);
  46. request.ContentLength = buffer.Length;
  47. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  48. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  49. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
  50. string result = reader.ReadToEnd();
  51. Debug.Log("人脸检测与属性分析:");
  52. Debug.Log(result);
  53. return result;
  54. }
  55. // 人脸融合
  56. public string facemerge()
  57. {
  58. string host = "https://aip.baidubce.com/rest/2.0/face/v1/merge?access_token=" + token;
  59. Encoding encoding = Encoding.Default;
  60. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
  61. request.Method = "post";
  62. request.KeepAlive = true;
  63. String str = "{\"image_template\":{\"image\":\"" + Base64Image02 +"\",\"image_type\":\"BASE64\",\"quality_control\":\"NONE\"},\"image_target\":{\"image\":\""+ Base64Image01 +"\",\"image_type\":\"BASE64\",\"quality_control\":\"NONE\"}}";
  64. byte[] buffer = encoding.GetBytes(str);
  65. request.ContentLength = buffer.Length;
  66. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  67. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  68. StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
  69. string result = reader.ReadToEnd();
  70. Debug.Log(result);
  71. string[] ArrayStr = result.Split(new string[] { "merge_image\":\"", "\"}}" }, StringSplitOptions.RemoveEmptyEntries);
  72. ReceiveBase64Str = ArrayStr[1];
  73. ReceiveBase64Str = ReceiveBase64Str.Replace("\\","");
  74. raw.texture = Base64ToTexter2d(ReceiveBase64Str); // 图片显示 Base64图片
  75. Debug.Log("人脸融合:");
  76. return ReceiveBase64Str;
  77. }
  78. public void Save(string sb,string name)
  79. {
  80. //写文件 文件名为save.text
  81. //这里的FileMode.create是创建这个文件,如果文件名存在则覆盖重新创建
  82. FileStream fs = new FileStream(Application.dataPath + "/" + name+".txt", FileMode.Create);
  83. //存储时时二进制,所以这里需要把我们的字符串转成二进制
  84. byte[] bytes = new UTF8Encoding().GetBytes(sb.ToString());
  85. fs.Write(bytes, 0, bytes.Length);
  86. //每次读取文件后都要记得关闭文件
  87. fs.Close();
  88. }
  89. /// <summary>
  90. /// 图片转换成base64编码文本
  91. /// </summary>
  92. public string ImgToBase64String(string path)
  93. {
  94. FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
  95. byte[] buffer = new byte[fs.Length];
  96. fs.Read(buffer, 0, (int)fs.Length);
  97. string base64String = Convert.ToBase64String(buffer);
  98. // Debug.Log("获取当前图片base64为---" + base64String);
  99. return base64String;
  100. }
  101. /// <summary>
  102. /// base64编码文本转换成Texture
  103. /// </summary>
  104. private Texture2D Base64ToTexter2d(string Base64STR)
  105. {
  106. Texture2D pic = new Texture2D(200, 200);
  107. byte[] data = System.Convert.FromBase64String(Base64STR);
  108. //File.WriteAllBytes(Application.dataPath + "/BuildImage/Base64ToSaveImage.png", data);
  109. pic.LoadImage(data);
  110. return pic;
  111. }
  112. /// <summary>
  113. /// base64编码文本转换成图片
  114. /// </summary>
  115. public void Base64ToImg(Image imgComponent,string str)
  116. {
  117. string base64 = str;
  118. byte[] bytes = Convert.FromBase64String(base64);
  119. Texture2D tex2D = new Texture2D(100, 100);
  120. tex2D.LoadImage(bytes);
  121. Sprite s = Sprite.Create(tex2D, new Rect(0, 0, tex2D.width, tex2D.height), new Vector2(0.5f, 0.5f));
  122. imgComponent.sprite = s;
  123. Resources.UnloadUnusedAssets();
  124. }
  125. }
  126. }

结果如下:

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/123607
推荐阅读
相关标签
  

闽ICP备14008679号