Python 版图片分类指南

借助 MediaPipe 图像分类器任务,您可以对图像执行分类。您可以使用此任务在训练时定义的一组类别中识别某张图片所代表的含义。以下说明介绍了如何在 Python 中使用图片分类器。

您可以观看 Web 演示,了解此任务的实际效果。如需详细了解此任务的功能、模型和配置选项,请参阅概览

代码示例

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

如果您要为 Raspberry Pi 实现图片分类器,请参阅 Raspberry Pi 示例应用

初始设置

本部分介绍了专门针对使用图片分类器而设置开发环境和代码项目的关键步骤。如需了解如何为使用 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 图像分类器任务需要使用与此任务兼容的经过训练的模型。如需详细了解适用于图片分类器的经过训练的模型,请参阅任务概览“模型”部分

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

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

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

base_options = BaseOptions(model_asset_path=model_path)

创建任务

使用 create_from_options 函数创建任务。create_from_options 函数接受配置选项,包括运行模式、显示名称语言区域、结果数上限、置信度阈值、类别许可名单和拒绝列表。如需详细了解配置选项,请参阅配置概览

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

映像

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ImageClassifier = mp.tasks.vision.ImageClassifier
ImageClassifierOptions = mp.tasks.vision.ImageClassifierOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = ImageClassifierOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    max_results=5,
    running_mode=VisionRunningMode.IMAGE)

with ImageClassifier.create_from_options(options) as classifier:
  # The classifier is initialized. Use it here.
  # ...
    

视频

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ImageClassifier = mp.tasks.vision.ImageClassifier
ImageClassifierOptions = mp.tasks.vision.ImageClassifierOptions
VisionRunningMode = mp.tasks.vision.RunningMode

options = ImageClassifierOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    max_results=5,
    running_mode=VisionRunningMode.VIDEO)

with ImageClassifier.create_from_options(options) as classifier:
  # The classifier is initialized. Use it here.
  # ...
    

直播

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ImageClassifierResult = mp.tasks.vision.ImageClassifier.ImageClassifierResult
ImageClassifier = mp.tasks.vision.ImageClassifier
ImageClassifierOptions = mp.tasks.vision.ImageClassifierOptions
VisionRunningMode = mp.tasks.vision.RunningMode

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

options = ImageClassifierOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.tflite'),
    running_mode=VisionRunningMode.LIVE_STREAM,
    max_results=5,
    result_callback=print_result)

with ImageClassifier.create_from_options(options) as classifier:
  # The classifier is initialized. Use it here.
  # ...
    

如需查看创建用于图片的图片分类器的完整示例,请参阅代码示例

配置选项

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

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

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

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

LIVE_STREAM:输入数据(例如来自摄像头)的直播的模式。在此模式下,必须调用 resultListener,以设置用于异步接收结果的监听器。
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
display_names_locale 设置任务模型元数据中提供的显示名(如果有)要使用的标签语言。英语的默认值为 en。您可以使用 TensorFlow Lite Metadata Writer API 向自定义模型的元数据添加本地化标签 语言区域代码 en
max_results 设置要返回的得分最高的分类结果的数量上限(可选)。如果小于 0,将返回所有可用的结果。 任何正数 -1
score_threshold 设置预测分数阈值,以替换模型元数据中提供的阈值(如果有)。低于此值的结果会被拒绝。 任意浮点数 未设置
category_allowlist 设置允许的类别名称的可选列表。如果为非空,则类别名称不在此集合中的分类结果将被滤除。系统会忽略重复或未知的类别名称。 此选项与 category_denylist 互斥,如果同时使用这两者,就会引发错误。 任何字符串 未设置
category_denylist 设置不允许使用的类别名称的可选列表。如果非空,则类别名称在此集合中的分类结果将被滤除。系统会忽略重复或未知的类别名称。此选项与 category_allowlist 互斥,同时使用这两者会导致错误。 任何字符串 未设置
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 Classifier API 会返回输入图片或帧内对象的可能类别。

映像

# Perform image classification on the provided single image.
classification_result = classifier.classify(mp_image)
    

视频

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

# Perform image classification on the video frame.
classification_result = classifier.classify_for_video(mp_image, frame_timestamp_ms)
    

直播


# Send the latest frame to perform image classification.
# Results are sent to the `result_callback` provided in the `ImageClassifierOptions`.
classifier.classify_async(mp_image, frame_timestamp_ms)
    

请注意以下几点:

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

如需查看创建用于图片的图片分类器的完整示例,请参阅代码示例

处理和显示结果

运行推理后,图像分类器任务会返回一个 ImageClassifierResult 对象,其中包含输入图片或帧中对象的可能类别列表。

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

ImageClassifierResult:
 Classifications #0 (single classification head):
  head index: 0
  category #0:
   category name: "/m/01bwb9"
   display name: "Passer domesticus"
   score: 0.91406
   index: 671
  category #1:
   category name: "/m/01bwbt"
   display name: "Passer montanus"
   score: 0.00391
   index: 670

在以下设备上运行 Bird Classifier 即可获得这个结果:

图片分类器示例代码演示了如何显示从任务返回的分类结果。如需了解详情,请参阅代码示例