快速入门:创建一个用于检测和定格图像中人脸的 Python 脚本Quickstart: Create a Python script to detect and frame faces in an image

在本快速入门中,你将创建一个 Python 脚本,它通过 Python SDK 使用 Azure 人脸 API 来检测远程图像中的人脸。In this quickstart, you will create a Python script that uses the Azure Face API, through the Python SDK, to detect human faces in a remote image. 此应用程序显示一个选定的图像,然后围绕每个检测到的人脸绘制一个框。The application displays a selected image and draws a frame around each detected face.

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

必备条件Prerequisites

获取人脸 SDKGet the Face SDK

通过打开命令提示符并运行以下命令来安装人脸 Python SDK:Install the Face Python SDK by opening the command prompt and running the following command:

pip install azure-cognitiveservices-vision-face

在图像中检测人脸Detect Faces in an image

创建名为 FaceQuickstart.py 的新 Python 脚本并添加以下代码 。Create a new Python script named FaceQuickstart.py and add the following code. 此代码处理人脸检测的核心功能。This code handles the core functionality of face detection. 需将 <Subscription Key> 替换为密钥的值。You will need to replace <Subscription Key> with the value of your key. 可能还需更改 BASE_URL 的值,以便使用密钥的正确区域标识符(如需包含所有区域终结点的列表,请参阅人脸 API 文档)。You may also need to change the value of BASE_URL to use the correct region identifier for your key (see the Face API docs for a list of all region endpoints). (可选)将 img_url 设置为要使用的图像的 URL。Optionally, set img_url to the URL of any image you'd like to use.

此脚本会通过调用 FaceClient.face.detect_with_url 方法来检测人脸,该方法可包装 检测 REST API 并返回人脸的列表。The script will detect faces by calling the FaceClient.face.detect_with_url method, which wraps the Detect REST API and returns a list of faces.

from azure.cognitiveservices.vision.face import FaceClient

# Replace with a valid subscription key (keeping the quotes in place).
KEY = '<Subscription Key>'

# Replace with your regional Base URL
BASE_URL = 'https://api.cognitive.azure.cn/face/v1.0/'

faceClient = FaceClient(BASE_URL, CognitiveServicesCredentials(KEY))

# You can use this example JPG or replace the URL below with your own URL to a JPEG image.
img_url = 'https://raw.githubusercontent.com/Microsoft/Cognitive-Face-Windows/master/Data/detection1.jpg'
faces = faceClient.face.detect_with_url(img_url)
print(faces)

备注

如果创建的人脸 API 的 LocationChina East 2,则需要将 URL https://api.cognitive.azure.cn/face/v1.0/ 替换为 https://chinaeast2.api.cognitive.azure.cn/face/v1.0/If the Location of the face api you created is China East 2, you need to replace the url https://api.cognitive.azure.cn/face/v1.0/ with https://chinaeast2.api.cognitive.azure.cn/face/v1.0/.

试用应用Try the app

使用 python FaceQuickstart.py 命令运行此应用。Run the app with the command python FaceQuickstart.py. 此时会在控制台窗口中出现文本响应,如下所示:You should get a text response in the console window, like the following:

[{'faceId': '26d8face-9714-4f3e-bfa1-f19a7a7aa240', 'faceRectangle': {'top': 124, 'left': 459, 'width': 227, 'height': 227}}]

输出表示检测到的人脸列表。The output represents a list of detected faces. 列表中的每项都是一个 dict 实例,其中 faceId 是检测到的人脸的唯一 ID,faceRectangle 说明检测到的人脸的位置。Each item in the list is a dict instance where faceId is a unique ID for the detected face and faceRectangle describes the position of the detected face.

备注

人脸 ID 在 24 小时后过期;如需长期保存人脸数据,则需对其进行显式存储。Face IDs expire after 24 hours; you will need to store face data explicitly if you wish to keep it long-term.

绘制人脸矩形Draw face rectangles

使用通过上一命令接收到的坐标,可在图像上绘制矩形,以可视方式呈现每张人脸。Using the coordinates that you received from the previous command, you can draw rectangles on the image to visually represent each face. 需安装 Pillow (pip install pillow) 才能使用 Pillow 图像模块。You will need to install Pillow (pip install pillow) to use the Pillow Image Module. FaceQuickstart.py 顶部添加以下代码:At the top of FaceQuickstart.py, add the following code:

import requests
from io import BytesIO
from PIL import Image, ImageDraw

然后,在脚本底部添加以下代码。Then, at the bottom of your script, add the following code. 此代码会创建一个用于分析矩形坐标的简单函数,并使用 Pillow 在原始图像上绘制矩形。This code creates a simple function for parsing the rectangle coordinates, and uses Pillow to draw rectangles on the original image. 然后,它会在默认的图像查看器中显示图像。Then, it displays the image in your default image viewer.

# Convert width height to a point in a rectangle


def getRectangle(faceDictionary):
    rect = faceDictionary['faceRectangle']
    left = rect['left']
    top = rect['top']
    bottom = left + rect['height']
    right = top + rect['width']
    return ((left, top), (bottom, right))


# Download the image from the url
response = requests.get(img_url)
img = Image.open(BytesIO(response.content))

# For each face returned use the face rectangle and draw a red box.
draw = ImageDraw.Draw(img)
for face in faces:
    draw.rectangle(getRectangle(face), outline='red')

# Display the image in the users default image browser.
img.show()

运行应用Run the app

系统可能会提示你先选择默认的图像查看器。You may be prompted to select a default image viewer first. 然后,会看到如下图像。Then, you should see an image like the following. 还会在控制台窗口中看到输出的矩形数据。You should also see the rectangle data printed in the console window.

一位年轻的妇女,其脸部周围绘制了一个红色矩形

后续步骤Next steps

本快速入门介绍了人脸 API Python SDK 的基本使用过程,并创建了一个脚本来检测并定格图像中的人脸。In this quickstart, you learned the basic process for using the Face API Python SDK and created a script to detect and frame faces in an image. 接下来,了解如何在更复杂的示例中使用 Python SDK。Next, explore the use of the Python SDK in a more complex example. 请转到 GitHub 上的认知人脸 Python 示例,将其克隆到项目文件夹,然后按 README.md 文件中的说明操作。Go to the Cognitive Face Python sample on GitHub, clone it to your project folder, and follow the instructions in the README.md file.