Python 版图片分类指南

借助 MediaPipe 图片分类器任务,您可以对图片进行分类。您可以使用此任务在训练时定义的一组类别中确定图片所代表的内容。以下说明介绍了如何将图片分类器与 Python 搭配使用。

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

代码示例

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

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

设置

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

软件包

图像分类器任务使用 mediapipe pip 软件包。您可以使用以下命令安装依赖项:

$ python -m pip install mediapipe
``` ### Imports

Import the following classes to access the Image Classifier task functions:

```python
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 种输入数据类型:静态图片、视频文件和实时视频直播。选择与输入数据类型对应的标签页,了解如何创建任务和运行推理。

Image

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

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

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 时才能使用 不适用 未设置

准备数据

将输入准备为图片文件或 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 Classifier API 会返回输入图片或画面中对象的可能类别。

Image

# 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

此结果是在以下平台上运行鸟类分类器后获得的:

一只家麻雀的特写照片

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