适用于 Python 的对象检测指南

借助 MediaPipe Object Detector 任务,您可以检测多类对象的是否存在和位置。以下说明介绍了如何在 Python 中使用对象检测器任务。GitHub 上提供了这些说明中描述的代码示例。

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

代码示例

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

如果您要为 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 Object Detector 任务需要使用与此任务兼容的经过训练的模型。如需详细了解对象检测器可用的经过训练的模型,请参阅任务概览“模型”部分

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

model_path = '/absolute/path/to/lite-model_efficientdet_lite0_detection_metadata_1.tflite'

使用 BaseOptions 对象 model_asset_path 参数指定要使用的模型的路径。如需查看代码示例,请参阅下一部分。

创建任务

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

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

映像

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

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

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

视频

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

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

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

直播

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
DetectionResult = mp.tasks.components.containers.detections.DetectionResult
ObjectDetector = mp.tasks.vision.ObjectDetector
ObjectDetectorOptions = mp.tasks.vision.ObjectDetectorOptions
VisionRunningMode = mp.tasks.vision.RunningMode

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

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

with ObjectDetector.create_from_options(options) as detector:
  # The detector is initialized. Use it here.
  # ...
    

如需查看创建用于图片的对象检测器的完整示例,请参阅代码示例

配置选项

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

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

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

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

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

准备数据

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

运行任务

您可以调用其中一个检测函数来触发推断。对象检测器任务将返回在输入图片或帧中检测到的对象。

映像

# Perform object detection on the provided single image.
detection_result = detector.detect(mp_image)
    

视频

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

# Perform object detection on the video frame.
detection_result = detector.detect_for_video(mp_image, frame_timestamp_ms)
    

直播


# Send the latest frame to perform object detection.
# Results are sent to the `result_callback` provided in the `ObjectDetectorOptions`.
detector.detect_async(mp_image, frame_timestamp_ms)
    

如需查看对图片运行对象检测器的完整示例,请参阅代码示例了解详情。

请注意以下几点:

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

处理和显示结果

运行推断时,对象检测器任务会返回一个 ObjectDetectionResult 对象,该对象描述它在输入图片中找到的对象。

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

ObjectDetectorResult:
 Detection #0:
  Box: (x: 355, y: 133, w: 190, h: 206)
  Categories:
   index       : 17
   score       : 0.73828
   class name  : dog
 Detection #1:
  Box: (x: 103, y: 15, w: 138, h: 369)
  Categories:
   index       : 17
   score       : 0.73047
   class name  : dog

下图显示了任务输出的可视化效果:

对象检测器示例代码演示了如何显示任务返回的检测结果。如需了解详情,请参阅代码示例