Python 图像分割指南

借助 MediaPipe Image Segmenter 任务,您可以根据用于应用视觉效果(例如背景模糊处理)的预定义类别将图片划分为多个区域。以下说明介绍了如何在 Python 语言中使用图片分割器。如需详细了解此任务的功能、模型和配置选项,请参阅概览

代码示例

Image Segmenter 的示例代码在 Python 中提供了此任务的完整实现,供您参考。此代码可帮助您测试此任务,并开始构建自己的图像分割器应用。只需使用网络浏览器,您就可以查看、运行和修改 Image Segmenter 示例代码

初始设置

本部分介绍了专门针对使用 Image Segmenter 来设置开发环境和代码项目的关键步骤。如需大致了解如何为使用 MediaPipe 任务设置开发环境(包括平台版本要求),请参阅 Python 设置指南。 您可以在 GitHub 上查看此示例的源代码

软件包

MediaPipe Image Segmenter 任务需要使用 mediapipe 软件包。您可以使用以下命令安装所需的依赖项:

$ python -m pip install mediapipe

导入

导入以下类来访问 Image Segmenter 任务函数:

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

模型

MediaPipe Image Segmenter 任务需要使用与此任务兼容的经过训练的模型。如需详细了解适用于图片分割器的经过训练的模型,请参阅任务概览模型部分。

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

model_path = '/absolute/path/to/model.tflite'

在 Model Name 参数中指定模型的路径,如下所示:

base_options = BaseOptions(model_asset_path=model_path)

创建任务

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

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

映像

BaseOptions = mp.tasks.BaseOptions
ImageSegmenter = mp.tasks.vision.ImageSegmenter
ImageSegmenterOptions = mp.tasks.vision.ImageSegmenterOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a image segmenter instance with the image mode:
options = ImageSegmenterOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.IMAGE,
    output_category_mask=True)
with ImageSegmenter.create_from_options(options) as segmenter:
  

视频

BaseOptions = mp.tasks.BaseOptions
ImageSegmenter = mp.tasks.vision.ImageSegmenter
ImageSegmenterOptions = mp.tasks.vision.ImageSegmenterOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a image segmenter instance with the video mode:
options = ImageSegmenterOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.VIDEO,
    output_category_mask=True)
with ImageSegmenter.create_from_options(options) as segmenter:
  

直播

BaseOptions = mp.tasks.BaseOptions
ImageSegmenter = mp.tasks.vision.ImageSegmenter
ImageSegmenterOptions = mp.tasks.vision.ImageSegmenterOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a image segmenter instance with the live stream mode:
def print_result(result: List[Image], output_image: Image, timestamp_ms: int):
    print('segmented masks size: {}'.format(len(result)))

options = ImageSegmenterOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.VIDEO,
    output_category_mask=True)
with ImageSegmenter.create_from_options(options) as segmenter:
    

配置选项

此任务为 Python 应用提供以下配置选项:

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

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

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

LIVE_STREAM:输入数据(例如来自摄像头)的直播的模式。在此模式下,必须调用 resultListener,以设置用于异步接收结果的监听器。
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
output_category_mask 如果设置为 True,则输出会包含一个 uint8 图片形式的分割掩码,其中每个像素值表示胜出类别值。 {True, False} False
output_confidence_masks 如果设置为 True,则输出将包含分割掩码(浮点值图片),其中每个浮点值表示类别的置信度分数映射。 {True, False} True
display_names_locale 设置任务模型元数据中提供的显示名(如果有)要使用的标签语言。英语的默认值为 en。您可以使用 TensorFlow Lite Metadata Writer API 向自定义模型的元数据添加本地化标签。语言区域代码 en
result_callback 设置结果监听器,以在图像分割器处于直播模式时异步接收分割结果。只能在跑步模式设为“LIVE_STREAM”时使用 N/A N/A

准备数据

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

映像

# 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)
    

视频

# Use OpenCV’s VideoCapture to load the input video.
# Load the frame rate of the video using OpenCV’s CV_CAP_PROP_FPS
# You need the frame rate 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)
    

直播

# 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)
    

如需查看代码示例,了解如何准备图片分割器的数据,请参阅代码示例

运行任务

图片分割器使用 segmentsegment_for_videosegment_async 函数来触发推断。对于图像分割,这涉及预处理输入数据、运行分割模型,以及对原始模型输出到分割后的掩码进行后处理。

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

映像

# Perform image segmentation on the provided single image.
# The image segmenter must be created with the image mode.
segmented_masks = segmenter.segment(mp_image)
    

视频

# Perform image segmentation on the provided single image.
# The image segmenter must be created with the video mode.
segmented_masks = segmenter.segment_for_video(mp_image, frame_timestamp_ms)
    

直播

# Send live image data to perform image segmentation.
# The results are accessible via the `result_callback` provided in
# the `ImageSegmenterOptions` object.
# The image segmenter must be created with the live stream mode.
segmenter.segment_async(mp_image, frame_timestamp_ms)
    

请注意以下几点:

  • 在视频模式或直播模式下运行时,您还必须为图像分割器任务提供输入帧的时间戳。
  • 在图片或视频模型中运行时,Image Segmenter 任务将阻塞当前线程,直到处理完输入图片或帧。

如需查看运行 Image Segmenter 推断的更完整示例,请参阅代码示例

处理和显示结果

图像分割器会输出 Image 数据列表。如果 output_typeCATEGORY_MASK,则输出是一个列表,其中包含单个分段蒙版(以 uint8 图片的形式表示)。像素表示识别出的输入图片的类别索引。如果 output_typeCONFIDENCE_MASK,则输出一个大小为类别编号的矢量。每个分割后的蒙版都是一张 [0,1] 范围内的浮点图片,表示属于该类别的像素的置信度分数。

以下各部分展示了此任务的输出数据示例:

类别置信度

下图显示了类别置信度掩码的任务输出的可视化效果。置信度掩码输出包含介于 [0, 1] 之间的浮点值。

原始图片和类别置信度遮盖输出。来自 Pascal VOC 2012 数据集的来源图片。

类别值

下图显示了类别值掩码的任务输出的可视化效果。类别掩码范围为 [0, 255],每个像素值代表模型输出的胜出类别索引。胜出类别索引在模型可以识别的类别中得分最高。

原始图片和类别掩码输出。来自 Pascal VOC 2012 数据集的来源图片。