Face Detection

Function

This API is used to detect, locate, and analyze the face in an input image, and output the key facial points and attributes.

Prerequisites:

Restrictions:
  • 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:
    1. The illumination should be greater than 200 lux and there is no light reflection or shadow caused by strong light.
    2. The overall image is clear without obvious motion blur and the face in it is not blocked.
    3. 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.
Suggestions:
  • 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.
  • It is recommended that the face resolution in an image be greater than 120 x 120.

URI

POST /v1/{project_id}/face-detect

Table 1 Path parameters

Parameter

Mandatory

Type

Description

project_id

Yes

String

Project ID. For details about how to obtain the ID, see Obtaining the Project ID, Account Name, and AK/SK.

Request Message

Table 2 Request header parameters

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.

Table 3 Request body parameters

Parameter

Mandatory

Type

Description

image_url

Either image_url, image_file, or image_base64 is mandatory.

String

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

Either image_file, image_url, or image_base64 is mandatory.

File

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

Either image_base64, image_file, or image_url is mandatory.

String

Image data (Base64-encoded). Its requirements are as follows:
  • The image size after Base64 encoding cannot exceed 8 MB. It is recommended that the image size be less than 1 MB.
  • The image is in JPG, JPEG, BMP, or PNG format.

attributes

No

String

Whether to return the facial attribute list. Multiple attributes are separated by commas (,). Currently, the following attributes are supported:
  • 0: Face posture
  • 2: Age
  • 3: Key facial point
  • 4: Dress (hat, glasses)
  • 5: Smiling face

Response Message

Table 4 Response body parameters

Parameter

Type

Description

faces

List

Detected face. For details about the DetectFace structure, see DetectFace.

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}/v1/{project_id}/face-detect
    Request Header:
    Content-Type: application/json
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
    
    Request Body:
    {
        "image_base64": "/9j/4AAQSkZJRgABAgEASABIAAD",
        "attributes": "0,2,3,4,5"
    }
  • Example request (Method 2: Use an image file.)
    POST https://{endpoint}/v1/{project_id}/face-detect
    Request Header:
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
    
    Request Body:
      image_file: File (image file)
      attributes: 0,2,3,4,5
  • Example request (Method 3: Use the image URL.)
    POST https://{endpoint}/v1/{project_id}/face-detect
    Request Header:
    Content-Type: application/json
    X-Auth-Token: MIINRwYJKoZIhvcNAQcCoIINODCCDTQCAQExDT...
    
    Request Body:
    {
        "image_url": "/BucketName/ObjectName",
        "attributes": "0,2,3,4,5"
    }
  • 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}
    
    url = "https://{endpoint}/v1/{project_id}/face-detect".format(endpoint=endpoint, project_id=project_id)
    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")  # Use Base64 encoding of images.
    body = {"image_base64": image_base64, "attributes": "0,2,3,4,5"}
    
    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.HttpHeaders;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    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 FaceDetect {
        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 and project_id with the actual ones.
            String url = "https://{{endpoint}}/v1/{{project_id}}/face-detect";
            // Replace image_base64 with the actual value.
            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

Response example (successful request)
{
  "faces": [
    {
      "bounding_box": {
        "width": 174,
        "top_left_y": 37,
        "top_left_x": 22,
        "height": 174
      },
      "attributes": {
        "age": 35,
        "smile": "yes",
        "dress": {
          "glass": "none",
          "hat": "none"
        },
        "headpose": {
          "pitch_angle": -3.8639126,
          "roll_angle": -3.988193,
          "yaw_angle": -1.0292832
        }
      },
      "landmark": {
      "eyebrow_contour": {
        "point": [
          {
            "x": 158.78517,
            "y": 90.02418
          },
          {
            "x": 150.86162,
            "y": 82.432076
          },
          {
            "x": 131.3591,
            "y": 80.78191
          },
          {
            "x": 121.39423,
            "y": 87.62841
          },
          {
            "x": 132.25839,
            "y": 88.44499
          },
          {
            "x": 149.63844,
            "y": 89.3718
          },
          {
            "x": 59.65225,
            "y": 99.64757
          },
          {
            "x": 65.96038,
            "y": 88.92635
          },
          {
            "x": 85.72037,
            "y": 85.07116
          },
          {
            "x": 97.09234,
            "y": 89.34221
          },
          {
            "x": 86.07851,
            "y": 92.297516
          },
          {
            "x": 67.51544,
            "y": 95.58905
          }
        ]
      },
      "eyes_contour": {
        "point": [
          {
            "x": 69.22003,
            "y": 105.52183
          },
          {
            "x": 81.599174,
            "y": 98.70017
          },
          {
            "x": 94.22879,
            "y": 103.18641
          },
          {
            "x": 82.32345,
            "y": 107.02255
          },
          {
            "x": 150.97876,
            "y": 99.29232
          },
          {
            "x": 137.91818,
            "y": 93.49849
          },
          {
            "x": 125.78866,
            "y": 100.8499
          },
          {
            "x": 138.81555,
            "y": 102.29028
          },
          {
            "x": 75.16096,
            "y": 100.01521
          },
          {
            "x": 75.6541,
            "y": 107.08471
          },
          {
            "x": 89.18221,
            "y": 106.11414
          },
          {
            "x": 88.87559,
            "y": 98.87617
          },
          {
            "x": 130.7761,
            "y": 95.49036
          },
          {
            "x": 131.64914,
            "y": 102.47154
          },
          {
            "x": 145.64833,
            "y": 101.04822
          },
          {
            "x": 145.52222,
            "y": 94.39164
          }
        ]
      },
      "face_contour": {
        "point": [
          {
            "x": 50.049454,
            "y": 104.4499
          },
          {
            "x": 52.502007,
            "y": 123.68245
          },
          {
            "x": 55.028637,
            "y": 143.12273
          },
          {
            "x": 59.972454,
            "y": 163.16571
          },
          {
            "x": 69.73235,
            "y": 180.53296
          },
          {
            "x": 81.76993,
            "y": 195.74933
          },
          {
            "x": 96.15602,
            "y": 210.08699
          },
          {
            "x": 115.32445,
            "y": 215.14973
          },
          {
            "x": 134.04883,
            "y": 209.08778
          },
          {
            "x": 147.96034,
            "y": 194.2003
          },
          {
            "x": 158.3112,
            "y": 178.27126
          },
          {
            "x": 165.62479,
            "y": 159.71454
          },
          {
            "x": 168.95554,
            "y": 139.12373
          },
          {
            "x": 169.59795,
            "y": 119.938416
          },
          {
            "x": 169.9221,
            "y": 99.658844
          }
        ]
      },
      "mouth_contour": {
        "point": [
          {
            "x": 82.56091,
            "y": 160.6078
          },
          {
            "x": 91.546906,
            "y": 154.97893
          },
          {
            "x": 101.45366,
            "y": 152.51962
          },
          {
            "x": 111.45223,
            "y": 153.75433
          },
          {
            "x": 122.52581,
            "y": 152.07089
          },
          {
            "x": 133.3687,
            "y": 152.31891
          },
          {
            "x": 142.48122,
            "y": 154.72552
          },
          {
            "x": 136.62144,
            "y": 167.81747
          },
          {
            "x": 126.79148,
            "y": 175.79927
          },
          {
            "x": 113.959526,
            "y": 179.32193
          },
          {
            "x": 99.90567,
            "y": 178.14986
          },
          {
            "x": 88.95302,
            "y": 172.11215
          },
          {
            "x": 95.30528,
            "y": 168.83522
          },
          {
            "x": 112.094025,
            "y": 170.73698
          },
          {
            "x": 129.00156,
            "y": 166.50134
          },
          {
            "x": 128.46986,
            "y": 156.3436
          },
          {
            "x": 111.70824,
            "y": 158.2964
          },
          {
            "x": 96.44703,
            "y": 158.49106
          },
          {
            "x": 111.8587,
            "y": 164.61029
          }
        ]
      },
      "nose_contour": {
        "point": [
          {
            "x": 100.12734,
            "y": 103.06376
          },
          {
            "x": 99.64418,
            "y": 121.0322
          },
          {
            "x": 92.39153,
            "y": 134.87288
          },
          {
            "x": 95.70406,
            "y": 140.70796
          },
          {
            "x": 113.04284,
            "y": 143.04053
          },
          {
            "x": 129.63658,
            "y": 138.64207
          },
          {
            "x": 131.6913,
            "y": 131.54257
          },
          {
            "x": 122.73644,
            "y": 119.520386
          },
          {
            "x": 119.106,
            "y": 102.450005
          },
          {
            "x": 102.1847,
            "y": 138.2676
          },
          {
            "x": 122.21693,
            "y": 137.64107
          },
          {
            "x": 112.65759,
            "y": 131.8112
          }
        ]
      }
    }
    }
  ]
}

Status code: 400

Example response (failed request)
{
  "error_code": "FRS.0019",
  "error_msg": "The service has not been subscribed."
}

Status Code

For details about the status code, see Status Codes.

Error Code

For details about the error code, see Error Codes.