C# 活体检测

活体检测有多种情形,本文所指:从摄像头获取的影像中判断是活体,还是使用了相片等静态图片。

场景描述

用户个人信息中上传了近照,当用户经过摄像头时进行身份识别。

此时,如果单纯的使用摄像头获取的影像进行人脸相似度比对,则举一张合适的相片对准摄像头也是可以通过的。于是检测摄像头前影像是否为活体的需求就产生了。

解决方案

使用百度AI开放平台,它免费开放一定并发量的该场景活体检测 API:
https://ai.baidu.com/tech/face/faceliveness

第一步,申请百度应用


点击“立即使用”,登录后“创建应用”,可以得到 API Key 与 Secret Key 等信息。

第二步,使用 API 进行活体检测

这里的场景比较简单,摄像头获取的影像可以保存为图片,则功能接口可以这样定义:给定图片(这里使用URL),判断其活体影像的概率。根据百度建议,概率设置为 99.5%,即达到此值或以上认为活体检测通过。

(1)获取 accessToken
accessToken 有效期为 30 天,因此,可以缓存起来使用。此为示例,时长又足够长,所以未加刷新机制。代码如下,其中,clientId 为百度应用中的 API Key,clientSecret 为百度应用中的 Secret Key。

public static class AccessToken
{
    // 有效期30天,缓存获取的 access token
    public static String TOKEN = null;

    // 百度云中开通对应服务应用的 API Key
    private static String clientId = "API Key";
    // 百度云中开通对应服务应用的 Secret Key
    private static String clientSecret = "Secret Key";

    public static String getAccessToken()
    {
        if (String.IsNullOrEmpty(TOKEN))
        {
            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;
            JObject jr = JObject.Parse(result);

            TOKEN = jr.Value<string>("access_token");
        }
        return TOKEN;
    } 
}

(2)调用 API 取得活体概率
API 的返回结果为 JSON,其中包括了活体概率,这里,方法直接返回 API 的 JSON 结果。

public class FaceLivenessHelper
{
    // 在线活体检测
    public static string FaceVerify(string imgUrl)
    {
        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 str = "[{\"image\":\"sfasq35sadvsvqwr5q...\",\"image_type\":\"BASE64\",\"face_field\":\"age,beauty,expression\"}]";
        String str = "[{\"image\":\"" + imgUrl + "\",\"image_type\":\"URL\",\"face_field\":\"age,beauty,expression\"}]";
        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;
    }
}

详细 API 文档见此:https://ai.baidu.com/docs#/Face-Liveness-V3/top

结果中:face_liveness 即表示“活体分数值”。

(3)应用
API 的调用结果中,error_code 为 0 时表示执行成功,此时,会有 result 属性表示计算的相关值,从中取出 face_liveness 即可,其值为 0 ~ 1之间。

string imgUrl = "------";
string result = FaceLivenessHelper.FaceVerify(imgUrl);
JObject jresult = JObject.Parse(result);
JObject lvresult = jresult.Value<JObject>("result");
// error_code 为 0 时表示执行成功,其它表示失败
if (jresult.Value<int>("error_code") == 0)
{
    double face_liveness = lvresult.Value<double>("face_liveness");
    // 活体率达到要求
    if (face_liveness >= 0.995)
    {
        // 通过检测
    }
}

猜你喜欢

转载自www.cnblogs.com/timeddd/p/11491033.html