Python 图像分割指南

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

代码示例

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

设置

本部分介绍了专门用于使用图片分割器设置开发环境和代码项目的关键步骤。如需了解有关设置开发环境以使用 MediaPipe 任务的一般信息(包括平台版本要求),请参阅 Python 设置指南。 您可以在 GitHub 上查看此示例的源代码

软件包

MediaPipe 图片分割器任务需要 mediapipe 软件包。您可以使用以下命令安装所需的依赖项:

$ python -m pip install mediapipe

导入

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

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

型号

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

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

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

在“Model Name”(模型名称)参数中指定模型的路径,如下所示:

base_options = BaseOptions(model_asset_path=model_path)

创建任务

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

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

Image

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:适用于单张图片输入的模式。

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

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 模式时异步接收分割结果。 仅当运行模式设置为 LIVE_STREAM 时才能使用 不适用 不适用

准备数据

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

Image

# 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 函数触发推理。对于图片分割,这涉及预处理输入数据、运行分割模型,以及将原始模型输出后处理为分割掩码。

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

Image

# 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 数据列表。如果 output_typeCATEGORY_MASK,则输出为包含单个分割蒙版(作为 uint8 图片)的列表。该像素表示输入图片的识别类别索引。如果 output_typeCONFIDENCE_MASK,则输出是一个大小为类别数的向量。每个分割掩码都是一个介于 [0,1] 范围内的浮点图片,表示属于该类别的像素的置信度得分。

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

类别置信度

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

两个女孩骑着马,还有一个女孩在马旁边走着 图片蒙版,用于勾勒出前一张照片中女孩和马的形状。系统捕获了图片左半部分的轮廓,但未捕获图片右半部分的轮廓

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

类别价值

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

两个女孩骑着马,还有一个女孩在马旁边走着 图片蒙版,用于勾勒出上图中女孩和马的形状。三个女孩和马匹的形状都已准确遮盖

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