1.接口说明

人脸比对接口用于比较两张人脸图片的相似度并给出同人判断。算法支持不同光照、角度、表情下的人脸特征提取,可用于开户核身、刷脸登录、风控拦截等场景。

1.1 主要功能

高精度比对:
自研深度模型,大量实网数据训练,鲁棒性强。
安全合规:
传输与存储均支持加密,满足实人认证与风控要求。
易集成:
提供多语言示例代码,支持APPCODE与签名双认证。

1.2 典型场景

线上开户、远程签约核身、刷脸登录、一人多号风险识别、公安/金融风控等。

2.请求信息

2.1 请求地址(URL)

POST http(s)://face-api.shiliuai.com/api/face_compare/v1

2.2 请求方式

POST

2.3 请求头(header)

参数 类型 说明
Content-Type string application/json
Authorization string 'APPCODE ' + 您的AppCode (注意英文空格)
参数 类型 说明
Content-Type string application/json
x-ca-key string 您的AppKey
x-ca-timestamp string 时间戳(毫秒)
x-ca-signature string 签名sign,md5(app_key&timestamp&app_secret)

2.4 请求体(body)

参数 类型 是否必填 说明
image_base64_1 string base64编码的图片文件1,像素范围:[15,8192],小于20M
image_base64_2 string base64编码的图片文件2,像素范围:[15,8192],小于20M

3.返回信息

3.1 返回类型

JSON

3.2 返回码

参数名 类型 说明
code int 200表示成功
message string 返回信息

3.3 返回字段

参数 类型 说明
code int 错误码
msg string 错误信息(英文)
msg_cn string 错误信息(中文)
success bool 请求是否成功
request_id string 唯一请求ID
data object 比对结果

3.3.1 data 信息

参数 参数类型 说明 举例
score float 相似度分数[-1, 1] 0.92

4.示例代码

4.1 Python

        # -*- coding: utf-8 -*-
        import requests
        import base64
        import json
                                                
        # 请求接口
        URL = "https://face-api.shiliuai.com/api/face_compare/v1"
                                                
        # 图片转base64
        def get_base64(file_path):
            with open(file_path, 'rb') as f:
                data = f.read()
            b64 = base64.b64encode(data).decode('utf8')
            return b64
                                                
                                                
        def demo(appcode, file_path_1, file_path_2):
            # 请求头
            headers = {
                'Authorization': 'APPCODE %s' % appcode,
                'Content-Type': 'application/json'
                }
                                                
            # 请求体
            b64_1 = get_base64(file_path_1)
            b64_2 = get_base64(file_path_2)
            data = {
                "image_base64_1": b64_1,
                "image_base64_2": b64_2
                }
                                                
             # 请求
            response = requests.post(url=URL, headers=headers, json=data)
            content = json.loads(response.content)
            print(content)
                                                
                                                
        if __name__=="__main__":
            appcode = "你的APPCODE"
            file_path_1 = "本地图片1路径"
            file_path_2 = "本地图片2路径"
            demo(appcode, file_path_1, file_path_2)    
        
        # -*- coding: utf-8 -*-
        import requests
        import base64
        import json
        import hashlib
        import time
                                                        
        # 请求接口
        URL = "https://face-api.shiliuai.com/api/face_compare/v1"
                                                        
        # 图片转base64
        def get_base64(file_path):
            with open(file_path, 'rb') as f:
                data = f.read()
            b64 = base64.b64encode(data).decode('utf8')
            return b64
                                                        
        # md5
        def md5(s):
            return hashlib.md5(s.encode("utf8")).hexdigest()
                                                        
                                                        
        def demo(app_key, app_secret, file_path_1, file_path_2):
            # 请求头
            t = int(time.time() * 1000)
            s = "%s&%s&%s" % (app_key, t, app_secret)
            sign = md5(s)
            headers = {'x-ca-key': app_key,
                    'x-ca-timestamp': t,
                    'x-ca-signature': sign,
                    "Content-Type": "application/json"}
                                                        
                                                        
            # 请求体
            b64_1 = get_base64(file_path_1)
            b64_2 = get_base64(file_path_2)
            data = {
                "image_base64_1": b64_1,
                "image_base64_2": b64_2
                }
                                                        
                                                        
             # 请求
            response = requests.post(url=URL, headers=headers, json=data)
            content = json.loads(response.content)
            print(content)
                                                        
                                                        
        if __name__=="__main__":
            app_key = "你的APP_KEY"
            app_secret = "你的APP_SECRET"
            file_path_1 = "本地图片1路径"
            file_path_2 = "本地图片2路径"
            demo(appcode, file_path_1, file_path_2)
        

4.2 PHP

        // 请求接口
        define("URL", "https://face-api.shiliuai.com/api/face_compare/v1");

        // 图片转base64
        function get_base64($file_path) {
            $data = file_get_contents($file_path);
            return base64_encode($data);
        }

        function demo($appcode, $file_path_1, $file_path_2) {
            // 请求头
            $headers = [
                'Authorization: APPCODE ' . $appcode,
                'Content-Type: application/json'
            ];

            // 请求体
            $b64_1 = get_base64($file_path_1);
            $b64_2 = get_base64($file_path_2);
            $data = [
                "image_base64_1" => $b64_1,
                "image_base64_2" => $b64_2
            ];

            // 初始化cURL
            $ch = curl_init();

            // 设置cURL选项
            curl_setopt($ch, CURLOPT_URL, URL);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过SSL验证(生产环境建议开启)

            // 执行请求
            $response = curl_exec($ch);

            // 检查错误
            if(curl_errno($ch)) {
                echo 'cURL Error: ' . curl_error($ch);
            } else {
                $result = json_decode($response, true);
                print_r($result);
            }

            // 关闭cURL资源
            curl_close($ch);
        }

        // 主程序
        if ($_SERVER['SCRIPT_FILENAME'] == __FILE__) {
            $appcode = "你的APPCODE";
            $file_path_1 = "本地图片1路径";
            $file_path_2 = "本地图片2路径";
            demo($appcode, $file_path_1, $file_path_2);
        }
                                                    
        
        function get_base64($path){
            if($fp = fopen($path, "rb", 0)) {
                $binary = fread($fp, filesize($path)); // 文件读取
                fclose($fp);
                $b64 = base64_encode($binary); // 转base64
            }else{
                $b64="";
                printf("%s 文件不存在", $path);
            }
            return $b64;
        }
    
        $url = "https://face-api.shiliuai.com/api/face_compare/v1";
        $img_path1 = "图片路径1";
        $img_path2 = "图片路径2";
        $method = "POST";
    
    
        //请求头
        $app_key = "你的app_key";
        $app_secret = "你的app_secret";
        $sign_string = $app_key . "&" . $timestamp . "&" . $app_secret;
        $sign = md5($sign_string);
    
        $headers = array();
        array_push($headers, "Content-Type:application/json");
        array_push($headers, "x-ca-key:" . $app_key);
        array_push($headers, "x-ca-timestamp:" . $timestamp);
        array_push($headers, "x-ca-signature:" . $sign);
    
    
        //请求体
        $b64_1 = get_base64($img_path1);
        $b64_2 = get_base64($img_path2);
        $data = array(
        $b64 = get_base64($img_path);
            "image_base64_1" => $b64_1,
            "image_base64_2" => $b64_2
        );
        $post_data = json_encode($data);
    
    
        //请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    
        $result = curl_exec($curl);
        var_dump($result);
                                                    
        

4.3 Java

        import com.alibaba.fastjson2.JSON;
        import com.alibaba.fastjson2.JSONObject;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.entity.StringEntity;
        import org.apache.http.impl.client.CloseableHttpClient;
        import org.apache.http.impl.client.HttpClients;
        import org.apache.http.util.EntityUtils;
        import org.apache.commons.io.FileUtils;
        import java.io.File;
        import java.io.IOException;
        import java.util.HashMap;
        import java.util.Map;
        import java.util.Base64;

        public class Main {

            public static String get_base64(String path) {
                String b64 = "";
                try {
                    // 使用Commons IO简化文件读取
                    byte[] content = FileUtils.readFileToByteArray(new File(path));
                    // 使用JDK自带的Base64
                    b64 = Base64.getEncoder().encodeToString(content);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return b64;
            }

            public static void main(String[] args) {
                String url = "https://face-api.shiliuai.com/api/face_compare/v1";
                String appcode = "你的APPCODE";
                String imgFile1 = "本地图片路径1";
                String imgFile2 = "本地图片路径2";

                Map headers = new HashMap<>();
                headers.put("Authorization", "APPCODE " + appcode);
                headers.put("Content-Type", "application/json");

                JSONObject requestObj = new JSONObject();
                requestObj.put("image_base64_1", get_base64(imgFile1));
                requestObj.put("image_base64_2", get_base64(imgFile2));
                String bodys = requestObj.toString();

                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    HttpPost httpPost = new HttpPost(url);
            
                    for (Map.Entry entry : headers.entrySet()) {
                        httpPost.addHeader(entry.getKey(), entry.getValue());
                    }
            
                    StringEntity entity = new StringEntity(bodys, "UTF-8");
                    httpPost.setEntity(entity);
            
                    HttpResponse response = httpClient.execute(httpPost);
            
                    int stat = response.getStatusLine().getStatusCode();
                    if (stat != 200) {
                        System.out.println("Http code: " + stat);
                        return;
                    }

                    String res = EntityUtils.toString(response.getEntity());
                    JSONObject res_obj = JSON.parseObject(res);
                    System.out.println(res_obj.toJSONString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
                                                    
        import com.alibaba.fastjson2.JSON;
        import com.alibaba.fastjson2.JSONObject;
        import org.apache.commons.io.FileUtils;
        import org.apache.http.HttpResponse;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.entity.StringEntity;
        import org.apache.http.impl.client.CloseableHttpClient;
        import org.apache.http.impl.client.HttpClients;
        import org.apache.http.util.EntityUtils;
        import java.io.File;
        import java.io.IOException;
        import java.util.HashMap;
        import java.util.Map;
        import java.util.Base64;
        import java.security.MessageDigest;
        import java.security.NoSuchAlgorithmException;

        public class Demo {

            public static String get_base64(String path) {
                String b64 = "";
                try {
                    File file = new File(path);
                    if (!file.exists()) {
                        System.err.println("文件不存在: " + path);
                        return b64;
                    }
                    byte[] content = FileUtils.readFileToByteArray(file);
                    b64 = Base64.getEncoder().encodeToString(content);
                } catch (IOException e) {
                    System.err.println("读取文件失败: " + e.getMessage());
                    e.printStackTrace();
                }
                return b64;
            }

            public static String MD5(String input) {
                try {
                    MessageDigest md = MessageDigest.getInstance("MD5");
                    byte[] messageDigest = md.digest(input.getBytes());

                    StringBuilder hexString = new StringBuilder();
                    for (byte b : messageDigest) {
                        String hex = Integer.toHexString(0xff & b);
                        if (hex.length() == 1)
                            hexString.append('0');
                        hexString.append(hex);
                    }
                    return hexString.toString();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                return null;
            }

            public static void main(String[] args) {
                String url = "https://face-api.shiliuai.com/api/face_compare/v1";
                String imgFile1 = "本地图片路径1";
                String imgFile2 = "本地图片路径2";
                String app_key = "你的APPKEY";
                String app_secret = "你的APPSECRET";
                String timestamp = System.currentTimeMillis() + "";
                String sign = MD5(app_key + "&" + timestamp + "&" + app_secret);

                Map headers = new HashMap<>();
                headers.put("Content-Type", "application/json");
                headers.put("x-ca-key", app_key);
                headers.put("x-ca-timestamp", timestamp);
                headers.put("x-ca-signature", sign);

                JSONObject requestObj = new JSONObject();
                requestObj.put("image_base64_1", get_base64(imgFile1));
                requestObj.put("image_base64_2", get_base64(imgFile2));
                String bodys = requestObj.toString();

                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    HttpPost httpPost = new HttpPost(url);
            
                    for (Map.Entry entry : headers.entrySet()) {
                        httpPost.addHeader(entry.getKey(), entry.getValue());
                    }
            
                    StringEntity entity = new StringEntity(bodys, "UTF-8");
                    httpPost.setEntity(entity);
            
                    HttpResponse response = httpClient.execute(httpPost);
            
                    int stat = response.getStatusLine().getStatusCode();
                    if (stat != 200) {
                        System.out.println("Http code: " + stat);
                        System.out.println("Http  " + EntityUtils.toString(response.getEntity()));
                        return;
                    }

                    String res = EntityUtils.toString(response.getEntity());
                    JSONObject res_obj = JSON.parseObject(res);
                    System.out.println(res_obj.toJSONString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
                                                    

4.4 C#

        using System.Text;
        using Newtonsoft.Json;
        using Newtonsoft.Json.Linq;

        namespace MyCSharpApp
        {
            public class Program
            {
                public static string GetBase64(string path)
                {
                    string b64 = "";
                    try
                    {
                        // 读取文件内容
                        byte[] content = File.ReadAllBytes(path);
                        // 转换为Base64
                        b64 = Convert.ToBase64String(content);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                    return b64;
                }

                public static async Task Main(string[] args)
                {
                    string url = "https://face-api.shiliuai.com/api/face_compare/v1"; // 请求接口
                    string appcode = "你的APPCODE";
                    string imgFile1 = "本地图片路径1";
                    string imgFile2 = "本地图片路径2";

                    // 设置请求头 
                    Dictionary headers = new Dictionary
                    {
                        { "Authorization", "APPCODE " + appcode }
                        // Content-Type 将在创建 StringContent 时设置
                    };

                    // 请求体
                    JObject requestObj = new JObject();
                    requestObj["image_base64_1"] = GetBase64(imgFile1);
                    requestObj["image_base64_2"] = GetBase64(imgFile2);
                    string body = requestObj.ToString();

                    try
                    {
                        using (HttpClient client = new HttpClient())
                        {
                            // 设置请求头
                            foreach (var header in headers)
                            {
                                client.DefaultRequestHeaders.Add(header.Key, header.Value);
                            }

                            // 创建请求内容 
                            StringContent content = new StringContent(body, Encoding.UTF8, "application/json");

                            // 发送请求并获取响应
                            HttpResponseMessage response = await client.PostAsync(url, content);

                            if (!response.IsSuccessStatusCode)
                            {
                                Console.WriteLine($"Http code: {(int)response.StatusCode}");
                                return;
                            }

                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            JObject resObj = JObject.Parse(responseContent);

                            Console.WriteLine(resObj.ToString(Formatting.Indented));
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }
         
        
        using System.Security.Cryptography;
        using System.Text;
        using Newtonsoft.Json;
        using Newtonsoft.Json.Linq;

        namespace MyCSharpApp
        {
            public class Program
            {
                public static string GetBase64(string path)
                {
                    string b64 = "";
                    try
                    {
                        // 读取文件内容
                        byte[] content = File.ReadAllBytes(path);
                        // 转换为Base64
                        b64 = Convert.ToBase64String(content);
                    }
                    catch (Exception e)
                    {
                        Console.Error.WriteLine("读取文件失败: " + e.Message);
                        Console.WriteLine(e.Message);
                    }
                    return b64;
                }

                public static string CalculateMD5(string input)
                {
                    try
                    {
                        // 创建MD5哈希提供程序
                        using (MD5 md5 = MD5.Create())
                        {
                            // 计算输入字符串的哈希值
                            byte[] inputBytes = Encoding.UTF8.GetBytes(input);
                            byte[] hashBytes = md5.ComputeHash(inputBytes);

                            // 将字节数组转换为十六进制字符串
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < hashBytes.Length; i++)
                            {
                                sb.Append(hashBytes[i].ToString("x2"));
                            }
                            return sb.ToString();
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                        return string.Empty; // 返回空字符串而不是null
                    }
                }

                public static async Task Main(string[] args)
                {
                    string url = "https://face-api.shiliuai.com/api/face_compare/v1"; // 请求接口
                    string imgFile1 = "本地图片路径1";
                    string imgFile2 = "本地图片路径2";
                    string app_key = "你的APPKEY";
                    string app_secret = "你的APPSECRET";
                    string timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds().ToString();
                    string sign = CalculateMD5(app_key + "&" + timestamp + "&" + app_secret);

                    // 设置请求头
                    Dictionary headers = new Dictionary
                    {
                        { "x-ca-key", app_key },
                        { "x-ca-timestamp", timestamp },
                        { "x-ca-signature", sign }
                        // Content-Type 将在创建 StringContent 时设置
                    };

                    // 请求体
                    JObject requestObj = new JObject();
                    requestObj["image_base64_1"] = GetBase64(imgFile1);
                    requestObj["image_base64_2"] = GetBase64(imgFile2);
                    string body = requestObj.ToString();
                    try
                    {
                        using (HttpClient client = new HttpClient())
                        {
                            // 设置请求头
                            foreach (var header in headers)
                            {
                                client.DefaultRequestHeaders.Add(header.Key, header.Value);
                            }

                            // 创建请求内容
                            StringContent content = new StringContent(body, Encoding.UTF8, "application/json");

                            // 发送请求并获取响应
                            HttpResponseMessage response = await client.PostAsync(url, content);

                            if (!response.IsSuccessStatusCode)
                            {
                                Console.WriteLine($"Http code: {(int)response.StatusCode}");
                                Console.WriteLine($"Http {await response.Content.ReadAsStringAsync()}");
                                return;
                            }

                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            JObject resObj = JObject.Parse(responseContent);

                            Console.WriteLine(resObj.ToString(Formatting.Indented));
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);
                    }
                }
            }
        }