更新时间:2024-04-28 GMT+08:00
分享

人脸搜索

功能介绍

人脸搜索是指在已有的人脸库中,查询与目标人脸相似的一张或者多张人脸,并返回相应的置信度。如果图片中包含多个人脸,选取图片中检测到的最大尺寸人脸作为检索的输入。

支持传入图片或者faceID进行人脸搜索。

前提条件:

请确保您已开通人脸识别服务,具体操作方法请参见申请服务

约束限制:
  • 只支持识别JPG、PNG、JPEG、BMP格式的图片。
  • application/json请求的body中,请使用标准Json格式。
  • Base64编码中请勿使用回车换行。
  • 系统不保存用户图片。
  • 图片大小小于8MB,由于过大图片会导致时延较长,并且图片信息量不大,建议小于1MB
  • 图片分辨率小于4096*4096,图片中人脸像素大于80*80,建议120*120以上。
  • 为保证识别效果,人脸图片建议要求如下:
    1. 光照大于200lux、无反光强光阴影现象。
    2. 人脸无遮挡、整体清晰无拖尾抖动等运动模糊。
    3. 侧脸不超过30°、俯仰角小于15°、偏转角小于15°、图片中人脸保持竖置正脸。
  • 其他的约束限制信息请参见约束与限制章节。
建议:
  • 由于过大图片对识别算法精度无明显提升,同时会导致时延较长,建议传入图片小于1MB,一般500KB左右足够。
  • OBS上存储的图片也建议小于1MB
  • 图片中人脸像素建议120*120以上。

调试

您可以在API Explorer中调试该接口,支持自动认证鉴权。API Explorer可以自动生成SDK代码示例,并提供SDK代码示例调试功能。

URI

POST /v2/{project_id}/face-sets/{face_set_name}/search

表1 路径参数

参数

是否必选

参数类型

描述

project_id

String

项目ID,获取方法请参见获取项目ID/账号名/AK/SK

face_set_name

String

人脸库名称,字符串长度1-64。

请求参数

表2 请求Header参数

参数

是否必选

参数类型

描述

X-Auth-Token

String

用户Token。

用于获取操作API的权限。获取方法请参见认证鉴权

Content-Type

String

发送的实体的MIME类型,参数值为“application/json”。

Enterprise-Project-Id

String

企业项目ID。FRS支持通过企业项目管理(EPS)对不同用户组和用户的资源使用,进行分账,当前仅支持按需计费模式。

获取方法:进入“企业项目管理”页面,单击企业项目名称,在企业项目详情页获取Enterprise-Project-Id(企业项目ID)。

说明:

创建企业项目后,在传参时,有以下三类场景。

  • 携带正确的ID,正常使用FRS服务,账单的企业项目会被分类到企业ID对应的企业项目中。
  • 携带格式正确但不存在的ID,正常使用FRS服务,账单的企业项目会显示对应不存在的企业项目ID。
  • 不携带ID或格式错误ID(包含特殊字符等),正常使用FRS服务,账单的企业项目会被分类到"default"中。
表3 请求Body参数

参数名

参数类型

是否必选

说明

image_url

String

与image_file、image_base64、face_id四选一

图片的URL路径,目前仅支持华为云上OBS的URL,使用时只需保证FRS有权限读取该OBS桶的数据。开通读取权限的操作请参见服务授权

image_file

File

与image_url、image_base64、face_id四选一

本地图片文件,图片不能超过8MB,建议小于1MB。上传文件时,请求格式为multipart。

image_base64

String

与image_file、image_url、face_id四选一

图像数据,Base64编码,要求:
  • Base64编码后大小不超过8MB,建议小于1MB
  • 图片为JPG/JPEG/BMP/PNG格式。

face_id

String

与image_file、image_base64、image_url四选一

导入人脸时,系统返回的人脸编号,即人脸ID。

top_n

Integer

返回查询到的最相似的N张人脸,N默认为10,取值范围[0,1000]。

N张人脸按照置信度降序排序,置信度越大越靠前。

threshold

Double

人脸相似度阈值,低于这个阈值则不返回,取值范围[0,1],一般情况下建议取值0.93,默认为0。

sort

JsonArray

支持字段排序,参考sort语法

filter

String

过滤条件,参考filter语法

return_fields

JsonArray

指定返回的自定义字段。

响应参数

状态码:200

表4 响应Body参数

参数

参数类型

描述

faces

Array of SearchFace objects

查找的人脸集合,详见SearchFace。 调用失败时无此字段。

表5 SearchFace

参数

参数类型

描述

bounding_box

BoundingBox object

人脸在图像中的位置。

similarity

Double

人脸搜索时用于被检索的相似度。

external_fields

Object

用户添加的额外自定义字段。

external_image_id

String

人脸所在的外部图片ID。

face_id

String

人脸ID,由系统内部生成的唯一ID。

表6 BoundingBox

参数

参数类型

描述

width

Integer

矩形框宽度。

top_left_y

Integer

矩形框左上角纵坐标。

top_left_x

Integer

矩形框左上角横坐标。

height

Integer

矩形框高度。

状态码: 400

表7 响应Body参数

参数

参数类型

描述

error_code

String

调用失败时的错误码,具体请参考错误码。 调用成功时无此字段。

error_msg

String

调用失败时的错误信息。 调用成功时无此字段。

请求示例

X-Auth-Token值获取方法请参见快速入门

  • 在人脸库中,查询与目标人脸相似的一张或者多张人脸,目标人脸通过图片的base64编码传入
    POST https://{endpoint}/v2/{project_id}/face-sets/showFaceSet/search
    Request Header:
    Content-Type: application/json
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
    
    Request Body:
    {
      "image_base64": "/9j/4AAQSkZJRgABAgEASABIAAD...",
      "sort" : [
        {
          "timestamp" : "asc"
        } 
      ],
      "return_fields" : ["timestamp", "id"],
      "filter" : "timestamp:12"
    }
  • 在人脸库中,查询与目标人脸相似的一张或者多张人脸,目标人脸通过图片文件传入
    POST https://{endpoint}/v2/{project_id}/face-sets/showFaceSet/search
    Request Header:
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
    
    Request Body:
    image_file: File(图片文件)
    return_fields: ["timestamp","id"]
    filter: timestamp:12
  • 在人脸库中,查询与目标人脸相似的一张或者多张人脸,目标人脸通过图片的url传入
    POST https://{endpoint}/v2/{project_id}/face-sets/showFaceSet/search
    Request Header:
    Content-Type: application/json
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
    
    Request Body:
    {
      "image_url":"https://<bucket-name>.<endpoint>/<object-name>",
      "sort" : [
        {
          "timestamp" : "asc"
        } 
      ],
      "return_fields" : ["timestamp", "id"],
      "filter" : "timestamp:12"
    }
  • 在人脸库中,查询与目标人脸相似的一张或者多张人脸,目标人脸通过人脸ID传入
    POST https://{endpoint}/v2/{project_id}/face-sets/showFaceSet/search
    Request Header: 
    Content-Type: application/json 
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT... 
    
    Request Body: 
    { 
      "face_id":"6KLB1Ktu", 
      "sort" : [ 
        { 
          "timestamp" : "asc" 
        }  
      ], 
      "return_fields" : ["timestamp", "id"], 
      "filter" : "timestamp:12" 
    }
  • 使用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}
    
    face_set_name = 'showFaceSet'
    url = "https://{endpoint}/v2/{project_id}/face-sets/{face_set_name}/search".format(
    endpoint=endpoint,project_id=project_id,face_set_name=face_set_name)
    image_file_path = r'./data/face-demo.png'
    with open(image_file_path, "rb") as bin_data:
        image_data = bin_data.read()
    image_base64 = base64.b64encode(image_data).decode("utf-8")
    body = {"image_base64": image_base64, "sort": [{"timestamp": "asc"}], "return_fields": ["timestamp", "id"], "filter": "timestamp:12"}
    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 FaceSearch {
        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和face_set_name需要替换成实际信息。
            String url = "https://{{endpoint}}/v2/{{project_id}}/face-sets/{{face_set_name}}/search";
            String jsonStr = "{\"image_base64\": \"/9j/4AAQSkZJRgABAgEASABIAAD...\", \"sort\": [{\"timestamp\": \"asc\"}], \"return_fields\": [\"timestamp\", \"id\"], \"filter\": \"timestamp:12\"}";
            String token = "对应region的token";
            String result = doPost(url, jsonStr, token, client);
            System.out.println(result);
        }
    }

响应示例

状态码:200

成功响应样例
{
  "faces": [
    {
      "bounding_box": {
        "width": 170,
        "top_left_y": 37,
        "top_left_x": 20,
        "height": 170
      },
      "similarity": 0.996146,
      "external_image_id": "123",
      "external_fields": {
        "id": "home",
        "timestamp": 12
      },
      "face_id": "6KLB1Ktu"
    },
    {
      "bounding_box": {
        "width": 170,
        "top_left_y": 37,
        "top_left_x": 20,
        "height": 170
      },
      "similarity": 0.996146,
      "external_image_id": "12",
      "external_fields": {
        "id": "home1",
        "timestamp": 12
      },
      "face_id": "PexOpqRj"
    }
  ]
}

状态码:400

失败响应样例
{
  "error_code": "FRS.0018",
  "error_msg": "The service inner error."
}

状态码

状态码请参见状态码

错误码

错误码请参见错误码

分享:

    相关文档

    相关产品