Face Add
Function
This API is used to add faces to a facial image library. All detected faces in the input facial image will be added to the library.
Prerequisites:
- Ensure that you have enabled FRS. For detailed operations, see Applying for FRS.
- Only images in JPG, PNG, JPEG, or BMP format can be recognized.
- Use standard JSON format in the body of the application/json request.
- Do not use carriage return characters in Base64 code.
- The system does not save images of users.
- The image size must be less than 8 MB. If the image is too large, the latency is long and the image information volume is small. It is recommended that the image size be less than 1 MB.
- The image resolution must be less than 4,096 x 2,160. The face resolution in an image must be greater than 80 x 80. It is recommended that the face resolution be greater than 120 x 120.
- To ensure the recognition effect, facial images need to meet the following requirements:
- The illumination should be greater than 200 lux and there is no light reflection or shadow caused by strong light.
- The overall image is clear without obvious motion blur and the face in it is not blocked.
- The side face angle does not exceed 30°, and the tilt angle and horizontal angle do not exceed 15°. The face in an image must be a vertically placed front face.
- For details about other restrictions, see Restrictions and Limitations.
- A larger image does not significantly improve the recognition algorithm precision but will cause a long latency. Therefore, you are advised to upload an image smaller than 1 MB. Generally, 500 KB is enough.
- It is recommended that the size of an image stored on OBS be less than 1 MB.
URI
POST /v2/{project_id}/face-sets/{face_set_name}/faces
| Parameter | Mandatory | Type | Description |
|---|---|---|---|
| project_id | Yes | String | Project ID. For details about how to obtain the project ID, see Obtaining the Project ID, Account Name, and AK/SK. |
| face_set_name | Yes | String | Name of a facial image library. |
Request Message
| Parameter | Mandatory | Type | Description |
|---|---|---|---|
| X-Auth-Token | Yes | String | User token. During API authentication using a token, the token is added to requests to obtain permissions for calling the API. The value of X-Subject-Token in the response header is the obtained token. |
| Parameter | Type | Mandatory | Description |
|---|---|---|---|
| image_url | String | Either image_url, image_file, or image_base64 is mandatory. | Image URL. Currently, only the URL of an OBS bucket on HUAWEI CLOUD is supported and FRS must have the permission to read data in the OBS bucket. For details about how to enable the read permission, see Service Authorization. |
| image_file | File | Either image_file, image_url, or image_base64 is mandatory. | Local image file, whose size cannot exceed 8 MB. It is recommended that the image size be less than 1 MB. The request format is Multipart. |
| image_base64 | String | Either image_base64, image_file, or image_url is mandatory. | Image data (Base64-encoded). Its requirements are as follows:
|
| external_image_id | String | No | External image ID specified by the user. It is bound to the current image. If the user does not provide one, it is generated by the system. The ID contains 1 to 36 characters, including letters, digits, hyphens (-), and underscores (_). Other special characters are not allowed. |
| external_fields | JSON | No | Custom data You need to define this field when creating a face library so that you can use custom fields to add faces. The uniqueness of JSON character strings is not verified. For details, see Customized Fields. |
Response Message
Status code: 200
| Parameter | Type | Description |
|---|---|---|
| face_set_name | String | Name of the facial image library. This parameter is not included when the API fails to be called. |
| face_set_id | String | ID of the facial image library. This parameter is not included when the API fails to be called. |
| faces | List | Face structure in the facial image library. For details, see FaceSetFace. This parameter is not included when the API fails to be called. |
| error_code | String | Error code returned after the API fails to be called. For details, see Error Codes. This parameter is not included when the API is successfully called. |
| error_msg | String | Error message returned after the API fails to be called. This parameter is not included when the API is successfully called. |
Example Requests
For details about how to obtain the value of X-Auth-Token, see Authentication.
- Example request (Method 1: Use a Base64-encoded image.)
POST https://{endpoint}/v2/{project_id}/face-sets/showFaceSet/faces Request Header: Content-Type: application/json X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT... Request Body: { "image_base64": "/9j/4AAQSkZJRgABAgEASABIAAD", "external_image_id": "imageID", "external_fields": { "timestamp": 12, "id": "home" } } - Example request (Method 2: Use an image file.)
POST https://{endpoint}/v2/{project_id}/face-sets/showFaceSet/faces Request Header: X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT... Request Body: image_file: File (image file) external_image_id: imageID external_fields: {"timestamp" : 12,"id" : "home"} - Example request (Method 3: Use the image URL.)
POST https://{endpoint}/v2/{project_id}/face-sets/showFaceSet/faces Request Header: Content-Type: application/json X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT... Request Body: { "image_url":"/BucketName/ObjectName", "external_image_id":"imageID", "external_fields" : { "timestamp": 12, "id": "home" } } - Sample code for a Python 3 request (For codes in other languages, refer to the following sample or use the FRS SDK.)
# -*- coding:utf-8 -*- import requests import base64 endpoint = 'Endpoint of the region where the service is enabled' project_id = 'Project ID of the region where the service is enabled' token = 'Actual token value obtained by the user' headers = {'Content-Type': 'application/json', 'X-Auth-Token': token} face_set_name = 'showFaceSet' url = "https://{endpoint}/v2/{project_id}/face-sets/{face_set_name}/faces".format( endpoint=endpoint,project_id=project_id,face_set_name=face_set_name) imagepath = r'./data/face-demo.png' with open(imagepath, "rb") as bin_data: image_data = bin_data.read() image_base64 = base64.b64encode(image_data).decode("utf-8") body = { "image_base64": image_base64, "external_image_id": "imageID", "external_fields": { "timestamp": 12, "id": "home" } } response = requests.post(url, headers=headers, json=body, verify=False) print(response.text)
- Sample code for a Java request (For codes in other languages, refer to the following sample or use the FRS SDK.)
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; /** * This demo is used only for tests. You are advised to use the SDK. * Before using this demo, configure the HttpClient JAR package. Obtain this package by downloading the SDK. */ public class AddFace { 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(); // Replace endpoint, project_id, and face_set_name with the actual ones. String url = "https://{{endpoint}}/v2/{{project_id}}/face-sets/{{face_set_name}}/faces"; String jsonStr = "{ \"image_base64\": \"/9j/4AAQSkZJRgABAgEASABIAAD...\"}"; String token = "Token of the corresponding region"; String result = doPost(url, jsonStr, token, client); System.out.println(result); } }
Example Responses
Status code: 200
{
"face_set_id": "T785tx1N",
"face_set_name": "showFaceSet",
"faces": [
{
"bounding_box": {
"width": 63,
"top_left_y": 100,
"top_left_x": 221,
"height": 63
},
"external_image_id": "Xr0phyap",
"external_fields" : {
"timestamp": 12,
"id": "home"
},
"face_id": "JLa9hYLl"
}
]
} Status code: 400
{
"error_code": "FRS.0404",
"error_msg": "Detect no face, can not add it to face set."
} Status Code
For details about the status code, see Status Codes.
Error Code
For details about the error code, see Error Codes.
Last Article: Facial Resource Management
Next Article: Face Query
Did this article solve your problem?
Thank you for your score!Your feedback would help us improve the website.