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

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

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

先决条件Prerequisites

设置 Node 环境Set up the Node environment

转到你要创建项目的文件夹并创建一个新文件 (facedetection.js)。Go to the folder where you'd like to create your project and create a new file, facedetection.js. 然后将 requests 模块安装到此项目中。Then install the requests module to this project. 这样,你的脚本就可以发出 HTTP 请求。This allows your scripts to make HTTP requests.

npm install request --save

编写 Node.js 脚本Write the Node.js script

将以下代码粘贴到 facedetection.js 中。Paste the following code into facedetection.js. 这些字段指定如何连接到人脸服务,以及在何处获取输入数据。These fields specify 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). 你可能希望更改 imageUrl 字段以指向自己的输入图像。You may wish to change the imageUrl field to point to your own input image.

'use strict';

const request = require('request');

// Replace <Subscription Key> with your valid subscription key.
const subscriptionKey = '<Subscription Key>';

const uriBase = 'https://api.cognitive.azure.cn/face/v1.0/detect';

const imageUrl =
    'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg';

然后,添加以下代码以调用人脸 API 并从输入图像中获取人脸属性数据。Then, add the following code to call the Face API and get face attribute data from the input image. returnFaceAttributes 字段指定要检索的人脸属性。The returnFaceAttributes field specifies which face attributes to retrieve. 可能需要更改此字符串,具体取决于预期用途。You may wish to change this string depending on your intended use.

// Request parameters.
const params = {
    'returnFaceId': 'true',
    'returnFaceLandmarks': 'false',
    'returnFaceAttributes': 'age,gender,headPose,smile,facialHair,glasses,' +
        'emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
};

const options = {
    uri: uriBase,
    qs: params,
    body: '{"url": ' + '"' + imageUrl + '"}',
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key' : subscriptionKey
    }
};

request.post(options, (error, response, body) => {
  if (error) {
    console.log('Error: ', error);
    return;
  }
  let jsonResponse = JSON.stringify(JSON.parse(body), null, '  ');
  console.log('JSON Response\n');
  console.log(jsonResponse);
});

保存并运行脚本Save and run the script

进行更改以后,请打开命令提示符并使用 node 命令运行该文件。After you've made your changes, open a command prompt and run the file with the node command.

node facedetection.js

应该会在控制台窗口中看到显示为 JSON 数据的人脸信息。You should see the face information displayed as JSON data in the console window. 例如:For example:

[
  {
    "faceId": "ae8952c1-7b5e-4a5a-a330-a6aa351262c9",
    "faceRectangle": {
      "top": 621,
      "left": 616,
      "width": 195,
      "height": 195
    },
    "faceAttributes": {
      "smile": 0,
      "headPose": {
        "pitch": 0,
        "roll": 6.8,
        "yaw": 3.7
      },
      "gender": "male",
      "age": 37,
      "facialHair": {
        "moustache": 0.4,
        "beard": 0.4,
        "sideburns": 0.1
      },
      "glasses": "NoGlasses",
      "emotion": {
        "anger": 0,
        "contempt": 0,
        "disgust": 0,
        "fear": 0,
        "happiness": 0,
        "neutral": 0.999,
        "sadness": 0.001,
        "surprise": 0
      },
      "blur": {
        "blurLevel": "high",
        "value": 0.89
      },
      "exposure": {
        "exposureLevel": "goodExposure",
        "value": 0.51
      },
      "noise": {
        "noiseLevel": "medium",
        "value": 0.59
      },
      "makeup": {
        "eyeMakeup": true,
        "lipMakeup": false
      },
      "accessories": [],
      "occlusion": {
        "foreheadOccluded": false,
        "eyeOccluded": false,
        "mouthOccluded": false
      },
      "hair": {
        "bald": 0.04,
        "invisible": false,
        "hairColor": [
          {
            "color": "black",
            "confidence": 0.98
          },
          {
            "color": "brown",
            "confidence": 0.87
          },
          {
            "color": "gray",
            "confidence": 0.85
          },
          {
            "color": "other",
            "confidence": 0.25
          },
          {
            "color": "blond",
            "confidence": 0.07
          },
          {
            "color": "red",
            "confidence": 0.02
          }
        ]
      }
    }
  },
  {
    "faceId": "b1bb3cbe-5a73-4f8d-96c8-836a5aca9415",
    "faceRectangle": {
      "top": 693,
      "left": 1503,
      "width": 180,
      "height": 180
    },
    "faceAttributes": {
      "smile": 0.003,
      "headPose": {
        "pitch": 0,
        "roll": 2,
        "yaw": -2.2
      },
      "gender": "female",
      "age": 56,
      "facialHair": {
        "moustache": 0,
        "beard": 0,
        "sideburns": 0
      },
      "glasses": "NoGlasses",
      "emotion": {
        "anger": 0,
        "contempt": 0.001,
        "disgust": 0,
        "fear": 0,
        "happiness": 0.003,
        "neutral": 0.984,
        "sadness": 0.011,
        "surprise": 0
      },
      "blur": {
        "blurLevel": "high",
        "value": 0.83
      },
      "exposure": {
        "exposureLevel": "goodExposure",
        "value": 0.41
      },
      "noise": {
        "noiseLevel": "high",
        "value": 0.76
      },
      "makeup": {
        "eyeMakeup": false,
        "lipMakeup": false
      },
      "accessories": [],
      "occlusion": {
        "foreheadOccluded": false,
        "eyeOccluded": false,
        "mouthOccluded": false
      },
      "hair": {
        "bald": 0.06,
        "invisible": false,
        "hairColor": [
          {
            "color": "black",
            "confidence": 0.99
          },
          {
            "color": "gray",
            "confidence": 0.89
          },
          {
            "color": "other",
            "confidence": 0.64
          },
          {
            "color": "brown",
            "confidence": 0.34
          },
          {
            "color": "blond",
            "confidence": 0.07
          },
          {
            "color": "red",
            "confidence": 0.03
          }
        ]
      }
    }
  }
]

后续步骤Next steps

在本快速入门中,你编写了一个 Node.js 脚本,该脚本调用 Azure 人脸 API,以便检测图像中的人脸并返回其属性。In this quickstart, you wrote a Node.js script that calls the Azure Face API to detect faces in an image and return their attributes. 接下来,请浏览人脸 API 参考文档,以便进行详细的了解。Next, explore the Face API reference documentation to learn more.