快速入门:使用 REST API 和 Java 检测图像中的人脸Quickstart: Detect faces in an image using the REST API and Java

在本快速入门中,请使用 Azure 人脸 REST API 和 Java 检测图像中的人脸。In this quickstart, you will use the Azure Face REST API with Java to detect human faces in an image.

如果没有 Azure 订阅,请在开始前创建一个试用帐户If you don't have an Azure subscription, create a Trial Account before you begin.

先决条件Prerequisites

  • 人脸 API 订阅密钥。A Face API subscription key. 可以按照创建认知服务帐户中的说明订阅人脸 API 服务并获取密钥。You can follow the instructions in Create a Cognitive Services account to subscribe to the Face API service and get your key.
  • 任何所选的 Java IDE。Any Java IDE of your choice.

创建 Java 项目Create the Java project

  1. 在 IDE 中创建新的命令行 Java 应用,并使用 main 方法添加 Main 类。Create a new command line Java app in your IDE and add a Main class with a main method.
  2. 将以下库导入到你的 Java 项目中。Import the following libraries into your Java project. 如果使用 Maven,则为每个库提供 Maven 坐标。If you're using Maven, the Maven coordinates are provided for each library.

添加人脸检测代码Add face detection code

打开项目的 main 类。Open the main class of your project. 在这里,请添加加载图像和检测人脸所需的代码。Here, you will add the code needed to load images and detect faces.

导入程序包Import packages

将下列 import 语句添加到文件顶部。Add the following import statements to the top of the file.

// This sample uses Apache HttpComponents:
// http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/
// https://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/

import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

添加必要的字段Add essential fields

Main 类替换为以下代码。Replace the Main class with the following code. 该数据指定如何连接到人脸服务,以及在何处获取输入数据。This data specifies how to connect to the Face service and where to get the input data. 需使用订阅密钥的值更新 subscriptionKey 字段,并且可能需要更改 uriBase 字符串,使之包含正确的区域标识符(如需包含所有区域终结点的列表,请参阅人脸 API 文档)。You'll need to update the subscriptionKey field with the value of your subscription key, and you may need to change the uriBase string so that it contains the correct region identifier (see the Face API docs for a list of all region endpoints). 可能还需要将 imageWithFaces 值设置为一个路径,使之指向另一图像文件。You may also wish to set the imageWithFaces value to a path that points to a different image file.

faceAttributes 字段只是一个列表,包含特定类型的属性。The faceAttributes field is simply a list of certain types of attributes. 它将指定要检索的有关已检测人脸的信息。It will specify which information to retrieve about the detected faces.

public class Main {
    // Replace <Subscription Key> with your valid subscription key.
    private static final String subscriptionKey = "<Subscription Key>";

    private static final String uriBase = "https://api.cognitive.azure.cn/face/v1.0/detect";

    private static final String imageWithFaces =
        "{\"url\":\"https://upload.wikimedia.org/wikipedia/commons/c/c3/RH_Louise_Lillian_Gish.jpg\"}";

    private static final String faceAttributes =
        "age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";

调用人脸检测 REST APICall the face detection REST API

通过以下代码添加 main方法。Add the main method with the following code. 它构造一个针对人脸 API 的 REST 调用,以便检测远程图像(faceAttributes 字符串指定要检索的人脸属性)中的人脸信息。It constructs a REST call to the Face API to detect face information in the remote image (the faceAttributes string specifies which face attributes to retrieve). 然后,它将输出数据写入到 JSON 字符串。Then it writes the output data to a JSON string.

    public static void main(String[] args) {
        HttpClient httpclient = HttpClientBuilder.create().build();

        try
        {
            URIBuilder builder = new URIBuilder(uriBase);

            // Request parameters. All of them are optional.
            builder.setParameter("returnFaceId", "true");
            builder.setParameter("returnFaceLandmarks", "false");
            builder.setParameter("returnFaceAttributes", faceAttributes);

            // Prepare the URI for the REST API call.
            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);

            // Request headers.
            request.setHeader("Content-Type", "application/json");
            request.setHeader("Ocp-Apim-Subscription-Key", subscriptionKey);

            // Request body.
            StringEntity reqEntity = new StringEntity(imageWithFaces);
            request.setEntity(reqEntity);

            // Execute the REST API call and get the response entity.
            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

分析 JSON 响应Parse the JSON response

直接在以前的代码下添加以下块,以便将返回的 JSON 数据转换成更加易于读取的格式,然后再将其输出到控制台。Directly below the previous code, add the following block, which converts the returned JSON data into a more easily readable format before printing it to the console. 最后,关闭 try-catch 块、main 方法和 Main 类。Finally, close out the try-catch block, the main method, and the Main class.

            if (entity != null)
            {
                // Format and display the JSON response.
                System.out.println("REST Response:\n");

                String jsonString = EntityUtils.toString(entity).trim();
                if (jsonString.charAt(0) == '[') {
                    JSONArray jsonArray = new JSONArray(jsonString);
                    System.out.println(jsonArray.toString(2));
                }
                else if (jsonString.charAt(0) == '{') {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    System.out.println(jsonObject.toString(2));
                } else {
                    System.out.println(jsonString);
                }
            }
        }
        catch (Exception e)
        {
            // Display error message.
            System.out.println(e.getMessage());
        }
    }
}

运行应用程序Run the app

编译并运行代码。Compile the code and run it. 成功的响应会以易于读取的 JSON 格式在控制台窗口中显示人脸数据。A successful response will display Face data in easily readable JSON format in the console window. 例如:For example:

[{
  "faceRectangle": {
    "top": 131,
    "left": 177,
    "width": 162,
    "height": 162
  },
  "faceAttributes": {
    "makeup": {
      "eyeMakeup": true,
      "lipMakeup": true
    },
    "facialHair": {
      "sideburns": 0,
      "beard": 0,
      "moustache": 0
    },
    "gender": "female",
    "accessories": [],
    "blur": {
      "blurLevel": "low",
      "value": 0.06
    },
    "headPose": {
      "roll": 0.1,
      "pitch": 0,
      "yaw": -32.9
    },
    "smile": 0,
    "glasses": "NoGlasses",
    "hair": {
      "bald": 0,
      "invisible": false,
      "hairColor": [
        {
          "color": "brown",
          "confidence": 1
        },
        {
          "color": "black",
          "confidence": 0.87
        },
        {
          "color": "other",
          "confidence": 0.51
        },
        {
          "color": "blond",
          "confidence": 0.08
        },
        {
          "color": "red",
          "confidence": 0.08
        },
        {
          "color": "gray",
          "confidence": 0.02
        }
      ]
    },
    "emotion": {
      "contempt": 0,
      "surprise": 0.005,
      "happiness": 0,
      "neutral": 0.986,
      "sadness": 0.009,
      "disgust": 0,
      "anger": 0,
      "fear": 0
    },
    "exposure": {
      "value": 0.67,
      "exposureLevel": "goodExposure"
    },
    "occlusion": {
      "eyeOccluded": false,
      "mouthOccluded": false,
      "foreheadOccluded": false
    },
    "noise": {
      "noiseLevel": "low",
      "value": 0
    },
    "age": 22.9
  },
  "faceId": "49d55c17-e018-4a42-ba7b-8cbbdfae7c6f"
}]

后续步骤Next steps

在本快速入门中,你创建了一个简单的 Java 控制台应用程序,该应用程序可以将 REST 调用与 Azure 人脸 API 配合使用,以便检测图像中的人脸并返回其属性。In this quickstart, you created a simple Java console application that uses REST calls with the Azure Face API to detect faces in an image and return their attributes. 接下来,请了解如何在 Android 应用程序中更充分地使用此功能。Next, learn how to do more with this functionality in an Android application.