Python 版图片嵌入指南

借助 MediaPipe Image Embedder 任务,您可以将图片数据转换为数字表示,以完成与机器学习相关的图片处理任务,例如比较两张图片的相似度。以下说明介绍了如何在 Python 中使用图片嵌入器。

如需详细了解此任务的功能、模型和配置选项,请参阅概览

代码示例

Image Embedder 的示例代码在 Python 中提供了此任务的完整实现,以供您参考。此代码可帮助您测试此任务并开始构建自己的图片嵌入器。借助 Google Colab,您只需使用网络浏览器即可查看、运行和修改图片嵌入器示例代码。您可以在 GitHub 上查看此示例的源代码。

初始设置

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

软件包

图片嵌入器用于对 mediapipe pip 软件包执行任务。您可以安装以下依赖项:

$ python -m pip install mediapipe

导入

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

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

模型

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

选择并下载模型,然后将其存储在本地目录中。您可以使用推荐的 MobileNetV3 模型。

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

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

base_options = BaseOptions(model_asset_path=model_path)

创建任务

您可以使用 create_from_options 函数创建任务。create_from_options 函数接受配置选项来设置嵌入器选项。如需详细了解配置选项,请参阅配置概览

Image Embedder 任务支持 3 种输入数据类型:静态图片、视频文件和直播视频流。选择与输入数据类型对应的标签页,了解如何创建任务并运行推断。

映像

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ImageEmbedder = mp.tasks.vision.ImageEmbedder
ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = ImageEmbedderOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    quantize=True,
    running_mode=VisionRunningMode.IMAGE)

with ImageEmbedder.create_from_options(options) as embedder:
  # The embedder is initialized. Use it here.
  # ...
    

视频

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ImageEmbedder = mp.tasks.vision.ImageEmbedder
ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = ImageEmbedderOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    quantize=True,
    running_mode=VisionRunningMode.VIDEO)

with ImageEmbedder.create_from_options(options) as embedder:
  # The embedder is initialized. Use it here.
  # ...
    

直播

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ImageEmbedderResult = mp.tasks.vision.ImageEmbedder.ImageEmbedderResult
ImageEmbedder = mp.tasks.vision.ImageEmbedder
ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions
VisionRunningMode = mp.tasks.vision.RunningMode

def print_result(result: ImageEmbedderResult, output_image: mp.Image, timestamp_ms: int):
    print('ImageEmbedderResult result: {}'.format(result))

options = ImageEmbedderOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    running_mode=VisionRunningMode.LIVE_STREAM,
    quantize=True,
    result_callback=print_result)

with ImageEmbedder.create_from_options(options) as embedder:
  # The embedder is initialized. Use it here.
  # ...
    

配置选项

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

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

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

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

LIVE_STREAM:输入数据(例如来自摄像头)的直播的模式。在此模式下,必须调用 resultListener,以设置用于异步接收结果的监听器。
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
l2_normalize 是否以 L2 范数归一化返回的特征向量。 仅当模型尚未包含原生 L2_NORMALIZATION TFLite 运算时,才可使用此选项。在大多数情况下,情况都是如此,L2 归一化是通过 TFLite 推断实现的,因此无需使用此选项。 Boolean False
quantize 是否应通过标量量化将返回的嵌入量化为字节。嵌入被隐式假定为单位范数,因此任何维度的值都必须在 [-1.0, 1.0] 之间。如果不属于这种情况,请使用 l2_normalize 选项。 Boolean False
result_callback 设置结果监听器,以在图片嵌入器处于直播模式时异步接收嵌入结果。只能在跑步模式设为“LIVE_STREAM”时使用 N/A 未设置

准备数据

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

映像

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)
    

运行任务

您可以调用与您的跑步模式对应的嵌入函数以触发推断。Image Embedder API 将返回输入图片或帧的嵌入矢量。

映像

# Perform image embedding on the provided single image.
embedding_result = embedder.embed(mp_image)
    

视频

# Calculate the timestamp of the current frame
frame_timestamp_ms = 1000 * frame_index / video_file_fps

# Perform image embedding on the video frame.
embedding_result = embedder.embed_for_video(mp_image, frame_timestamp_ms)
    

直播


# Send the latest frame to perform image embedding.
# Results are sent to the `result_callback` provided in the `ImageEmbedderOptions`.
embedder.embed_async(mp_image, frame_timestamp_ms)
    

请注意以下几点:

  • 在视频模式或直播模式下运行时,您还必须为图片嵌入器任务提供输入帧的时间戳。
  • 在图片或视频模型中运行时,图片嵌入器任务将阻塞当前线程,直到处理完输入图片或帧。
  • 在直播模式下运行时,Image Embedder 任务不会阻塞当前线程,但会立即返回结果。每当处理完输入帧时,它都会使用嵌入结果调用其结果监听器。如果在图片嵌入器任务正忙于处理另一帧时调用 embedAsync 函数,则该任务会忽略新的输入帧。

处理和显示结果

运行推断后,Image Embedder 任务会返回 ImageEmbedderResult 对象,该对象包含输入图片或帧中对象的可能类别列表。

下面显示了此任务的输出数据示例:

ImageEmbedderResult:
  Embedding #0 (sole embedding head):
    float_embedding: {0.0, 0.0, ..., 0.0, 1.0, 0.0, 0.0, 2.0}
    head_index: 0

通过嵌入以下图片获得此结果:

您可以使用 ImageEmbedder.cosine_similarity 函数比较两个嵌入的相似度。如需查看示例,请参阅以下代码。

# Compute cosine similarity.
similarity = ImageEmbedder.cosine_similarity(
  embedding_result.embeddings[0],
  other_embedding_result.embeddings[0])