Python 人脸特征点检测指南

借助 MediaPipe Face Landmarker 任务,您可以检测图片和视频中的人脸特征点和面部表情。您可以使用此任务来识别人脸表情,并应用脸部滤镜和效果来创建虚拟头像。此任务使用可处理单张图片或连续图片流的机器学习 (ML) 模型。该任务会输出 3D 面部地标、融合变形得分(表示面部表情的系数),以便实时推断详细的面部表面,以及用于执行效果渲染所需的转换矩阵。

这些说明中介绍的代码示例可在 GitHub 上找到。如需详细了解此任务的功能、模型和配置选项,请参阅概览

代码示例

人脸地标注示例代码提供了此任务的完整 Python 实现,供您参考。此代码可帮助您测试此任务,并开始构建自己的人脸地标定位器。您只需使用网络浏览器即可查看、运行和修改 人脸地标示例代码

如果您要为 Raspberry Pi 实现人脸标志检测器,请参阅 Raspberry Pi 示例应用

设置

本部分介绍了专门用于使用 Face Landmarker 设置开发环境和代码项目的关键步骤。如需了解有关设置开发环境以使用 MediaPipe 任务的一般信息(包括平台版本要求),请参阅 Python 设置指南

软件包

MediaPipe Face Landmarker 任务需要 mediapipe PyPI 软件包。您可以使用以下命令安装和导入这些依赖项:

$ python -m pip install mediapipe

导入

导入以下类以访问 Face Landmarker 任务函数:

import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision

型号

MediaPipe 人脸地标任务需要与此任务兼容的训练模型。如需详细了解适用于人脸地标检测器的可用训练模型,请参阅任务概览的“模型”部分

选择并下载模型,然后将其存储在本地目录中:

model_path = '/absolute/path/to/face_landmarker.task'

使用 BaseOptions 对象 model_asset_path 参数指定要使用的模型的路径。如需查看代码示例,请参阅下一部分。

创建任务

MediaPipe Face Landmarker 任务使用 create_from_options 函数来设置任务。create_from_options 函数接受要处理的配置选项的值。如需详细了解配置选项,请参阅配置选项

以下代码演示了如何构建和配置此任务。

这些示例还展示了图片、视频文件和直播的任务构建变体。

Image

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceLandmarker = mp.tasks.vision.FaceLandmarker
FaceLandmarkerOptions = mp.tasks.vision.FaceLandmarkerOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = FaceLandmarkerOptions(
    base_options=BaseOptions(model_asset_path=model_path),
    running_mode=VisionRunningMode.IMAGE)

with FaceLandmarker.create_from_options(options) as landmarker:
  # The landmarker is initialized. Use it here.
  # ...
    

视频

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceLandmarker = mp.tasks.vision.FaceLandmarker
FaceLandmarkerOptions = mp.tasks.vision.FaceLandmarkerOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face landmarker instance with the video mode:
options = FaceLandmarkerOptions(
    base_options=BaseOptions(model_asset_path=model_path),
    running_mode=VisionRunningMode.VIDEO)

with FaceLandmarker.create_from_options(options) as landmarker:
  # The landmarker is initialized. Use it here.
  # ...
    

直播

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
FaceLandmarker = mp.tasks.vision.FaceLandmarker
FaceLandmarkerOptions = mp.tasks.vision.FaceLandmarkerOptions
FaceLandmarkerResult = mp.tasks.vision.FaceLandmarkerResult
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a face landmarker instance with the live stream mode:
def print_result(result: FaceLandmarkerResult, output_image: mp.Image, timestamp_ms: int):
    print('face landmarker result: {}'.format(result))

options = FaceLandmarkerOptions(
    base_options=BaseOptions(model_asset_path=model_path),
    running_mode=VisionRunningMode.LIVE_STREAM,
    result_callback=print_result)

with FaceLandmarker.create_from_options(options) as landmarker:
  # The landmarker is initialized. Use it here.
  # ...
    

如需查看有关创建要与图片搭配使用的面部地标的完整示例,请参阅代码示例

配置选项

此任务针对 Python 应用提供了以下配置选项:

选项名称 说明 值范围 默认值
running_mode 设置任务的运行模式。共有三种模式:

IMAGE:适用于单张图片输入的模式。

视频:视频的解码帧的模式。

LIVE_STREAM:输入数据(例如来自摄像头)的直播模式。在此模式下,必须调用 resultListener 以设置监听器以异步接收结果。
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
num_faces FaceLandmarker 可检测的面部数量上限。仅当 num_faces 设置为 1 时才会应用平滑处理。 Integer > 0 1
min_face_detection_confidence 人脸检测被视为成功所需的最低置信度得分。 Float [0.0,1.0] 0.5
min_face_presence_confidence 人脸标志检测中人脸存在得分的最小置信度得分。 Float [0.0,1.0] 0.5
min_tracking_confidence 人脸跟踪被视为成功所需的最低置信度得分。 Float [0.0,1.0] 0.5
output_face_blendshapes 人脸特征点检测器是否输出人脸融合变形。 脸部混合形状用于渲染 3D 脸部模型。 Boolean False
output_facial_transformation_matrixes FaceLandmarker 是否输出面部转换矩阵。FaceLandmarker 使用矩阵将面部地标从规范化人脸模型转换为检测到的面部,以便用户对检测到的地标应用效果。 Boolean False
result_callback 设置结果监听器,以便在 FaceLandmarker 处于直播模式时异步接收地标结果。 仅当运行模式设置为 LIVE_STREAM 时才能使用 ResultListener N/A

准备数据

将输入准备为图片文件或 NumPy 数组,然后将其转换为 mediapipe.Image 对象。如果输入是视频文件或来自摄像头的实时流,您可以使用 OpenCV 等外部库将输入帧加载为 numpy 数组。

Image

import mediapipe as mp

# Load the input image from an image file.
mp_image = mp.Image.create_from_file('/path/to/image')

# Load the input image from a numpy array.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_image)
    

视频

import mediapipe as mp

# Use OpenCV’s VideoCapture to load the input video.

# Load the frame rate of the video using OpenCV’s CV_CAP_PROP_FPS
# You’ll need it to calculate the timestamp for each frame.

# Loop through each frame in the video using VideoCapture#read()

# Convert the frame received from OpenCV to a MediaPipe’s Image object.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
    

直播

import mediapipe as mp

# Use OpenCV’s VideoCapture to start capturing from the webcam.

# Create a loop to read the latest frame from the camera using VideoCapture#read()

# Convert the frame received from OpenCV to a MediaPipe’s Image object.
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=numpy_frame_from_opencv)
    

运行任务

人脸标志检测器使用 detectdetect_for_videodetect_async 函数触发推理。对于人脸地标检测,这涉及预处理输入数据和检测图片中的人脸。

以下代码演示了如何使用任务模型执行处理。

Image

# Perform face landmarking on the provided single image.
# The face landmarker must be created with the image mode.
face_landmarker_result = landmarker.detect(mp_image)
    

视频

# Perform face landmarking on the provided single image.
# The face landmarker must be created with the video mode.
face_landmarker_result = landmarker.detect_for_video(mp_image, frame_timestamp_ms)
    

直播

# Send live image data to perform face landmarking.
# The results are accessible via the `result_callback` provided in
# the `FaceLandmarkerOptions` object.
# The face landmarker must be created with the live stream mode.
landmarker.detect_async(mp_image, frame_timestamp_ms)
    

请注意以下几点:

  • 在视频模式或直播模式下运行时,还应向 Face Landmarker 任务提供输入帧的时间戳。
  • 在图片或视频模型中运行时,Face Landmarker 任务会阻塞当前线程,直到其处理完输入图片或帧。
  • 在直播模式下运行时,Face Landmarker 任务会立即返回,并且不会阻塞当前线程。每次处理完输入帧后,它都会调用带有检测结果的结果监听器。如果在 Face Landmarker 任务忙于处理其他帧时调用检测函数,该任务将忽略新的输入帧。

如需查看在图片上运行人脸地标注器的完整示例,请参阅代码示例了解详情。

处理和显示结果

Face Landmarker 会为每次运行检测返回一个 FaceLandmarkerResult 对象。结果对象包含每个检测到的人脸的面部网格,以及每个人脸地标的坐标。(可选)结果对象还可以包含表示面部表情的混合形状,以及用于对检测到的地标应用面部效果的面部转换矩阵。

以下是此任务的输出数据示例:

FaceLandmarkerResult:
  face_landmarks:
    NormalizedLandmark #0:
      x: 0.5971359014511108
      y: 0.485361784696579
      z: -0.038440968841314316
    NormalizedLandmark #1:
      x: 0.3302789330482483
      y: 0.29289937019348145
      z: -0.09489090740680695
    ... (478 landmarks for each face)
  face_blendshapes:
    browDownLeft: 0.8296722769737244
    browDownRight: 0.8096957206726074
    browInnerUp: 0.00035583582939580083
    browOuterUpLeft: 0.00035752105759456754
    ... (52 blendshapes for each face)
  facial_transformation_matrixes:
    [9.99158978e-01, -1.23036895e-02, 3.91213447e-02, -3.70770246e-01]
    [1.66496094e-02,  9.93480563e-01, -1.12779640e-01, 2.27719707e+01]
    ...

下图显示了任务输出的可视化结果:

一名男子,他的面部区域以几何图形标示出来,以指明面部的形状和尺寸

Face Landmarker 示例代码演示了如何显示从任务返回的结果,如需了解详情,请参阅代码示例