Python 版图片嵌入指南

借助 MediaPipe 图片嵌入任务,您可以将图片数据转换为数字表示法,以执行与机器学习相关的图片处理任务,例如比较两张图片的相似性。以下说明介绍了如何将图片嵌入工具与 Python 搭配使用。

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

代码示例

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

设置

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

软件包

图片嵌入任务使用 mediapipe pip 软件包。您可以使用以下命令安装该依赖项:

$ python -m pip install mediapipe

导入

导入以下类以访问图片嵌入器任务函数:

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

型号

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

选择并下载模型,然后将其存储在本地目录中。您可以使用推荐的 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 函数接受配置选项来设置嵌入选项。如需详细了解配置选项,请参阅配置概览

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

Image

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

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

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

准备数据

将输入准备为图片文件或 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)
    

运行任务

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

Image

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

请注意以下几点:

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

处理和显示结果

运行推理后,图片嵌入任务会返回一个 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])