百度AI开放平台提供了人脸识别功能,可以通过官网进行申请
得以得到一个百度提供的人脸识别服务应用
点击管理可以找到SDK下载界面,在unity3d中使用c#进行脚本的编写,选择下载c#SDK
现在的SDK版本为3.5.1,下载后得到的文件结构是这样的
可以根据.net库的不同选择使用不同的动态链接库文件
在我首次使用百度人脸识别时SDK版本为3.3.1
文件结构如下
其中AipSdk.dll提供了我们进行人脸识别开发需要的API,AipSdk.XML是对DLL的注释。thirdparty中包含了sdk的第三方依赖,Demo中是一些使用示例,可以进行参考。
解压后导入uinty3d项目中
导入时注意将第三方库文件一起导入
根据demo中给的程序进行学习使用
参考博客https://blog.csdn.net/dark00800/article/details/78191431后进行初步的使用
获取摄像头进行拍照,将照片上传给百度服务器得到返回结果,返回结果为json类型,解析后得到该照片中的人是否为库中所记录的成员,记录进入学习系统的学习者
using UnityEngine;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Collections.Generic;
using System;
using LitJson;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using System.Text;
public class takePhoto : MonoBehaviour
{
public string deviceName;//这个虽然public,但无需为其绑定变量,直接运行,默认调用,显示本地摄像机的名称
//接收返回的图片数据
WebCamTexture tex;
public UITexture QueryTex;
public UILabel Msg;
DateTime dt = DateTime.Now;
public static string dateTime;
public static string str;
public static string imagePath;
public static string isNewUser;
public static bool isTrue;
public static string oldUserID;
void OnGUI()
{
if (tex != null)
{
//捕获截图大小 —距X左屏距离 | 距Y上屏距离
GUI.DrawTexture(new Rect(Screen.width / 2 - 150, Screen.height / 2 - 190, 280, 200), tex);
}
}
private void Awake()
{
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
delegate (object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate,
System.Security.Cryptography.X509Certificates.X509Chain chain,
System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
return true; // always accept
};
}
// Use this for initialization
void Start()
{
StartCoroutine(OpCarame());
new GameObject().SetActive(false);
QueryTex.gameObject.SetActive(true);
Invoke("QueryLogin", 3);
}
void Update()
{
//tex.Pause();
//StartCoroutine(getTexture());
}
void OPenCarame(GameObject obj)
{
StartCoroutine(OpCarame());
//关闭按钮
obj.SetActive(false);
QueryTex.gameObject.SetActive(true);
}
void QueryLogin()
{
//捕获照片
tex.Pause();
StartCoroutine(getTexture());
}
///
/// 捕获窗口位置
///
public IEnumerator OpCarame()
{
yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
if (Application.HasUserAuthorization(UserAuthorization.WebCam))
{
WebCamDevice[] devices = WebCamTexture.devices;
deviceName = devices[0].name;
tex = new WebCamTexture(deviceName, 300, 300, 12);
tex.Play();
}
}
///
/// 获取截图
///
/// The texture.
public IEnumerator getTexture()
{
yield return new WaitForEndOfFrame();
Texture2D t = new Texture2D(400, 300);
t.ReadPixels(new Rect(Screen.width / 2 - 200, Screen.height / 2 - 50, 360, 300), 0, 0, false);
//距X左的距离 距Y屏上的距离
// t.ReadPixels(new Rect(220, 180, 200, 180), 0, 0, false);
t.Apply();
byte[] byt = t.EncodeToPNG();
//string path = Application.dataPath + "/Photoes/" + Time.time + ".jpg";
string path = "E:\\项目文档\\1.jpg";
File.WriteAllBytes(path, byt);
IdentifyDemo(path);
}
public void IdentifyDemo(string imgPath)
{
print(imgPath);
imagePath = imgPath;
var groupId = "123";//组名
var client = new Baidu.Aip.Face.Face("DnQ5npIM38mbAoelx81mnDkW", "kreCT0E3qnHfYPHKp9uVNkk9XdvFwrmv");//修改成自己的 key
var image = File.ReadAllBytes(imgPath);
// 调用人脸识别,可能会抛出网络等异常,请使用try/catch捕获
//var result = client.Identify(groupId, image);
//print(result);
// 如果有可选参数
var options = new Dictionary{
{"ext_fields", "faceliveness"}};
// 带参数调用人脸识别
try
{
var result2 = client.Identify(groupId, image, options);
decimal score = Convert.ToDecimal(result2["result"][0]["scores"][0]);
//print(result2);
//str = (string)result2["result_num"];
//int i = Int32.Parse(str);
//i++;
dateTime = dt.Year+""+ dt.Month + dt.Day + dt.Hour + dt.Minute + dt.Second;
if (score > 80)
{
isNewUser = "false";
//将是否是新用户写到文本中
Stream stream = File.Open(@".\isNewUser.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw1 = new StreamWriter(stream, Encoding.Default);
sw1.WriteLine(isNewUser);
sw1.Flush();
sw1.Close();
isTrue = false;
Msg.SetRect(Screen.width * 0.4f, Screen.height * 0.8f, 300, 60);
Msg.text = "欢迎再次使用英语学习系统!";
tex.Stop();//必须关闭摄像机
Debug.Log(result2["result"]);
String st = result2["result"].ToString();
string[] sArray = st.Split('"');
//Debug.Log(sArray[sArray.Length - 2]);
Debug.Log(sArray[3]);
oldUserID = sArray[3];
SceneManager.LoadScene("star");
}
else
{
isTrue = true;
isNewUser = "true";
//将是否是新用户写到文本中
Stream stream = File.Open(@".\isNewUser.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter sw1 = new StreamWriter(stream, Encoding.Default);
sw1.WriteLine(isNewUser);
sw1.Flush();
sw1.Close();
Msg.SetRect(Screen.width * 0.4f, Screen.height * 0.8f, 300, 60);
Msg.text = "欢迎新用户使用英语学习系统!";
client.UserAdd(dateTime, "", groupId, image, options);
Invoke("MsgInfo", 2);
// Invoke("QueryLogin", 3);
tex.Stop();//必须关闭摄像机
SceneManager.LoadScene("star");
}
}
catch
{
Msg.text = "登录失败!";
Invoke("MsgInfo", 3);
}
}
void MsgInfo()
{
Msg.text = "";
tex.Play();
}
}