
# 人脸比对 - CompareFace
#### 功能介绍
人脸比对是将两个人脸进行比对，来判断是否为同一个人，返回比对置信度。如果传入的图片中包含多个人脸，选取最大的人脸进行比对。
**前提条件：**
请确保您已开通[人脸识别服务](https://console.huaweicloud.com/frs/?locale=zh-cn#/frs/management/faceRecognized)，具体操作方法请参见[申请服务](https://support.huaweicloud.com/api-face/face_02_0006.html)。
**约束限制：**
- 人脸比对输入的两张图片总大小。
- 只支持识别JPG、PNG、JPEG、BMP格式的图片。
- application/json请求的body中，请使用标准Json格式。
- Base64编码中请勿使用回车换行。
- 系统不保存用户图片。
- 图片大小小于**8MB** ，由于过大图片会导致时延较长，并且图片信息量不大，建议**小于1MB**。
- 图片分辨率**小于4096\*4096** ，图片中人脸像素**大于80\*80**，建议120\*120以上。
- 为保证识别效果，人脸图片建议要求如下：
  1. 光照大于200lux、无反光强光阴影现象。
  
  2. 人脸完整无遮挡、整体清晰无拖尾抖动等运动模糊。
  
  3. 侧脸不超过30°、俯仰角小于15°、偏转角小于15°、图片中人脸保持竖置正脸。
   
- 具体的约束限制信息请参见[约束与限制](https://support.huaweicloud.com/api-face/face_02_0078.html)章节。
 
**建议：**
- 由于过大图片对识别算法精度无明显提升，同时会导致时延较长，建议传入图片**小于1MB** ，一般**500KB**左右足够。
- OBS上存储的图片也建议**小于1MB**。
- 图片中人脸像素建议**120\*120**以上。
 
#### 调试
您可以在[API Explorer](https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=FRS&api=CompareFaceByFile)中调试该接口，支持自动认证鉴权。API Explorer可以自动生成SDK代码示例，并提供SDK代码示例调试功能。
#### 授权信息
账号具备所有API的调用权限，如果使用账号下的IAM用户调用当前API，该IAM用户需具备调用API所需的权限，具体权限要求请参见[权限和授权项](https://support.huaweicloud.com/usermanual-face/face_01_0011.html)。
#### URI
POST /v2/{project_id}/face-compare
表1路径参数 
| 参数         | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                  |
|:---|:---|:---|:---|
| project_id | 是    | String | **参数解释：** 项目ID，获取方法请参见[获取项目ID/账号名/AK/SK](https://support.huaweicloud.com/api-face/face_02_0056.html)。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
   
#### 请求参数
表2请求Header参数 
| 参数                    | 是否必选 | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
|:---|:---|:---|:---|
| X-Auth-Token          | 是    | String | **参数解释：** 用户Token。用于获取操作API的权限。获取方法请参见[认证鉴权](https://support.huaweicloud.com/api-face/face_02_0004.html)。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| Content-Type          | 是    | String | **参数解释：** 发送的实体的MIME类型，参数值为"application/json"。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| Enterprise-Project-Id | 否    | String | **参数解释：** 企业项目ID。FRS支持通过企业项目管理（EPS）对不同用户组和用户的资源使用，进行分账，当前仅支持按需计费模式。 获取方法：进入"[企业项目管理](https://console.huaweicloud.com/eps/?#/eps/manager/projects)"页面，单击企业项目名称，在企业项目详情页获取Enterprise-Project-Id（企业项目ID）。 ![](https://support.huaweicloud.com/api-face/zh-cn_image_0000002572719678.png "点击放大") 说明： 创建企业项目后，在传参时，有以下三类场景。 - 携带正确的ID，正常使用FRS服务，账单的企业项目会被分类到企业ID对应的企业项目中。  - 携带格式正确但不存在的ID，正常使用FRS服务，账单的企业项目会显示对应不存在的企业项目ID。  - 不携带ID或格式错误ID（包含特殊字符等），正常使用FRS服务，账单的企业项目会被分类到"default"中。   **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
   
表3请求Body参数 
| 参数名           | 参数类型   | 是否必选                          | 说明                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
|:---|:---|:---|:---|
| image1_url    | String | 与image1_file、image1_base64三选一 | **参数解释：** 图片的URL路径，目前仅支持华为云上OBS的URL，使用时只需保证FRS有权限读取该OBS桶的数据。开通读取权限的操作请参见[服务授权](https://support.huaweicloud.com/api-face/face_02_0006.html)。 OBS URL格式如下，可在OBS控制台获取。 ``` https://BucketName.obs.xxxx.com/ObjectName ``` ![](https://support.huaweicloud.com/api-face/zh-cn_image_0000002614235047.png "点击放大") **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
| image1_file   | File   | 与image1_url、image1_base64三选一  | **参数解释：** 本地图片文件。 **约束限制：** - 图片不能超过**8MB** ，建议**小于1MB**。  - 上传文件时，请求格式为multipart。   **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                                    |
| image1_base64 | String | 与image1_file、image1_url三选一    | **参数解释：** 图像数据，Base64编码。 **约束限制：** - Base64编码后大小不超过**8MB** ，建议**小于1MB**。  - 图片为JPG/JPEG/BMP/PNG格式。   **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                       |
| image2_url    | String | 与image2_file、image2_base64三选一 | **参数解释：** 图片的URL路径，目前仅支持华为云上OBS的URL，且人脸识别服务有权限读取该OBS桶的数据。开通读取权限的操作请参见[服务授权](https://support.huaweicloud.com/api-face/face_02_0006.html)。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                                                                                                               |
| image2_file   | File   | 与image2_url、image2_base64三选一  | **参数解释：** 本地图片文件。 **约束限制：** - 图片不能超过**8MB** ，建议**小于1MB**。  - 上传文件时，请求格式为multipart。   **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                                           |
| image2_base64 | String | 与image2_file、image2_url三选一    | **参数解释：** 图像数据，Base64编码。 **约束限制：** - Base64编码后大小不超过**8MB** ，建议**小于1MB**。  - 图片为JPG/JPEG/BMP/PNG格式。   **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                                                                                                            |
   
#### 响应参数
**状态码：200**
表4响应Body参数 
| 参数          | 参数类型                                                      | 描述                                                                                                                                                                                                                                                                                                                                                                                           |
|:---|:---|:---|
| image1_face | [CompareFace] object | **参数解释：** 第1幅图像中检测到的人脸，DetectFace结构见[DetectFace](https://support.huaweicloud.com/api-face/face_02_0017.html)。 调用失败时无此字段。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
| image2_face | [CompareFace] object | **参数解释：** 第2幅图像中检测到的人脸，DetectFace结构见[DetectFace](https://support.huaweicloud.com/api-face/face_02_0017.html)。 调用失败时无此字段。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。  |
| similarity  | Double                                                    | **参数解释：** 人脸相似度，1表示最大，0表示最小，值越大表示越相似。一般情况下超过0.93即可认为是同一个人。如果图片质量较低，也会影响相似度。 调用失败时无此字段。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                                         |
   
 表5CompareFace 
| 参数           | 参数类型                                                      | 描述                                                                                                                                                                                                                                                                                            |
|:---|:---|:---|
| bounding_box | [BoundingBox] object | **参数解释：** 人脸在图像中的位置。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
   
 表6BoundingBox 
| 参数         | 参数类型    | 描述                                                                                                                                                                                                                                                                                                 |
|:---|:---|:---|
| width      | Integer | **参数解释：** 人脸图像所在矩形框的宽度。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。   |
| top_left_y | Integer | **参数解释：** 矩形框左上角纵坐标。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。          |
| top_left_x | Integer | **参数解释：** 矩形框左上角横坐标。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。         |
| height     | Integer | **参数解释：** 人脸图像所在矩形框的高度。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
   
**状态码： 400**
表7响应Body参数 
| 参数         | 参数类型   | 描述                                                                                                                                                                                                                                                                                                                                                                           |
|:---|:---|:---|
| error_code | String | **参数解释：** 调用失败时的错误码，具体请参考[错误码](https://support.huaweicloud.com/api-face/face_02_0045.html)。 调用成功时无此字段。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。 |
| error_msg  | String | **参数解释：** 调用失败时的错误信息。 调用成功时无此字段。 **约束限制：** 不涉及。 **取值范围：** 不涉及。 **默认取值：** 不涉及。                                                                         |
   
#### 请求示例
X-Auth-Token值获取方法请参见[快速入门](https://support.huaweicloud.com/qs-face/face_09_0003.html)。
- 判断两张人脸图片的相似度，待检测图片通过图片的base64编码传入
  ```
  POST https://{endpoint}/v2/{project_id}/face-compare
  Request Header:
  Content-Type: application/json
  X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
  Request Body:
  {
    "image1_base64":"/9j/4AAQSkZJRgABAgEASABIAAD...",
    "image2_base64":"/9j/4AAQSkZJRgABAgEASABIAAD..."
  }
  ```
  
- 判断两张人脸图片的相似度，待检测图片通过图片文件传入
  ```
  POST https://{endpoint}/v2/{project_id}/face-compare
  Request Header:
  X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
  Request Body:
  image1_file: File(图片文件)
  image2_file: File(图片文件)
  ```
  
- 判断两张人脸图片的相似度，待检测图片通过图片的url传入
  ```
  POST https://{endpoint}/v2/{project_id}/face-compare
  Request Header:
  Content-Type: application/json
  X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
  Request Body:
  {
    "image1_url":"https://<bucket-name>.<endpoint>/<object-name>",
    "image2_url":"https://<bucket-name>.<endpoint>/<object-name>"
  }
  ```
  
- 使用Python3语言检测两张人脸图片的相似度
  ```
  # -*- coding:utf-8 -*-
  import requests
  import base64
  endpoint = '开通服务所在region的人脸识别服务域名'
  project_id = '开通服务所在region的用户项目ID'
  token = '用户获取得到的实际token值'
  headers = {'Content-Type': 'application/json', 'X-Auth-Token': token}
  url = "https://{endpoint}/v2/{project_id}/face-compare".format(endpoint=endpoint, project_id=project_id)
  image1_file_path = r'./data/face-demo1.png'
  image2_file_path = r'./data/face-demo2.png'
  with open(image1_file_path, "rb") as bin_data:
  image1_data = bin_data.read()
  with open(image2_file_path, "rb") as bin_data:
  image2_data = bin_data.read()
  image1_base64 = base64.b64encode(image1_data).decode("utf-8")  
  image2_base64 = base64.b64encode(image2_data).decode("utf-8") 
  body = {"image1_base64": image1_base64,"image2_base64": image2_base64}
  response = requests.post(url, headers=headers, json=body, verify=False)
  print(response.text)
  ```
  

- 使用Java语言检测两张人脸图片的相似度
  ```
  import com.huawei.trace.http.apache.httpclient.TraceApacheHttpClientBuilder;
  import org.apache.http.HttpEntity;
  import org.apache.http.HttpHeaders;
  import org.apache.http.HttpResponse;
  import org.apache.http.client.config.RequestConfig;
  import org.apache.http.client.methods.HttpPost;
  import org.apache.http.config.Registry;
  import org.apache.http.config.RegistryBuilder;
  import org.apache.http.conn.socket.ConnectionSocketFactory;
  import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  import org.apache.http.conn.ssl.NoopHostnameVerifier;
  import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  import org.apache.http.entity.ContentType;
  import org.apache.http.entity.StringEntity;
  import org.apache.http.impl.client.CloseableHttpClient;
  import org.apache.http.impl.client.HttpClientBuilder;
  import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  import org.apache.http.ssl.SSLContextBuilder;
  import org.apache.http.ssl.TrustStrategy;
  import org.apache.http.util.EntityUtils;
  import java.io.IOException;
  import java.nio.charset.StandardCharsets;
  import java.security.KeyManagementException;
  import java.security.KeyStoreException;
  import java.security.NoSuchAlgorithmException;
  import java.security.cert.CertificateException;
  import java.security.cert.X509Certificate;
  import java.util.concurrent.TimeUnit;
  import javax.net.ssl.HostnameVerifier;
  import javax.net.ssl.SSLContext;
  /**
   * 此demo仅供测试使用，强烈建议使用SDK
   * 使用前需已配置HttpClient jar包。jar包可通过下载SDK获取
   */
  public class FaceCompare {
      protected static HttpClientBuilder buildClient(HttpClientBuilder httpClientBuilder) {
          SSLContext sslContext = null;
          try {
              sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                  public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                      return true;
                  }
              }).build();
          } catch (NoSuchAlgorithmException e) {
              throw new RuntimeException(e.getMessage());
          } catch (KeyManagementException e) {
              throw new RuntimeException(e.getMessage());
          } catch (KeyStoreException e) {
              throw new RuntimeException(e.getMessage());
          }
          httpClientBuilder.setSSLContext(sslContext);
          httpClientBuilder.setConnectionTimeToLive(30, TimeUnit.SECONDS);
          HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
          SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
          Registry<ConnectionSocketFactory> socketFactoryRegistry
              = RegistryBuilder.<ConnectionSocketFactory>create().register("http",
              PlainConnectionSocketFactory.getSocketFactory()).register("https", sslSocketFactory).build();
          PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
          connMgr.setMaxTotal(200);
          connMgr.setDefaultMaxPerRoute(100);
          httpClientBuilder.setConnectionManager(connMgr);
          return httpClientBuilder;
      }
      public static String doPost(String url, String jsonStr, String token, CloseableHttpClient client) {
          HttpPost post = new HttpPost(url);
          StringEntity entity = new StringEntity(jsonStr, ContentType.APPLICATION_JSON);
          post.setEntity(entity);
          post.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
          //time unit is milliseconds
          RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
          post.setConfig(requestConfig);
          post.setHeader("X-Auth-Token", token);
          HttpResponse response = null;
          String result = "";
          try {
              response = client.execute(post);
              HttpEntity responseBody = response.getEntity();
              if (responseBody == null) {
                  System.out.println("the response body is null.");
                  return result;
              } else {
                  byte[] byteStream = EntityUtils.toByteArray(responseBody);
                  System.arraycopy(byteStream, 0, new byte[byteStream.length], 0, byteStream.length);
                  result = new String(byteStream, StandardCharsets.UTF_8);
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
          return result;
      }
      public static void main(String[] args) {
          CloseableHttpClient client = buildClient(TraceApacheHttpClientBuilder.create()).build();
          // endpoint和project_id需要替换成实际信息。
          String url = "https://{{endpoint}}/v2/{{project_id}}/face-compare";
          // image_base64需要替换成实际的值
          String jsonStr = "{ \"image1_base64\": \"/9j/4AAQSkZJRgABAgEASABIAAD...\",\"image2_base64\": \"/9j/4AAQSkZJRgABAgEASABIAAD...\"}";
          String token = "对应region的token";
          String result = doPost(url, jsonStr, token, client);
          System.out.println(result);
      }
  }
  ```
  
 
#### 响应示例
**状态码：200**
成功响应样例
```
{
  "image1_face": {
    "bounding_box": {
      "width": 174,
      "top_left_y": 37,
      "top_left_x": 22,
      "height": 174
    }
  },
  "similarity": 0.4078676104545593,
  "image2_face": {
    "bounding_box": {
      "width": 118,
      "top_left_y": 28,
      "top_left_x": 94,
      "height": 118
    }
  }
}
```
**状态码：400**
失败响应样例
```
{
  "error_code": "FRS.0501",
  "error_msg": "Detect no face, check out your picture."
}
```
#### 状态码
状态码请参见[状态码](https://support.huaweicloud.com/api-face/face_02_0082.html)。
#### 错误码
错误码请参见[错误码](https://support.huaweicloud.com/api-face/face_02_0045.html)。
