适用于 Python 的对象检测指南

借助 MediaPipe 对象检测器任务,您可以检测多个对象是否存在 对象的类别。以下说明介绍了如何使用对象检测器 使用 Python。本说明中描述的代码示例可以在 GitHub

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

代码示例

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

如果要针对 Raspberry Pi 实现对象检测器,请参阅 Raspberry Pi 示例 app

设置

本部分介绍了设置开发环境和 专门用于对象检测器的代码项目。有关 设置开发环境以使用 MediaPipe 任务,包括 平台版本要求,请参阅 Python 设置指南

<ph type="x-smartling-placeholder">

软件包

对象检测器任务需要 mediapipe pip 软件包。您可以安装 所需的软件包:

$ python -m pip install mediapipe

导入

导入以下类以访问“对象检测器”任务函数:

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

型号

MediaPipe 对象检测器任务需要一个与此任务兼容的经过训练的模型 任务。如需详细了解对象检测器可用的经过训练的模型,请参阅 任务概览的“模型”部分

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

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 将可选的最高评分检测结果数上限设置为 return。 任何正数 -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)
    

有关对图片运行对象检测器的完整示例,请参阅 代码示例

请注意以下几点:

  • 在视频模式或直播模式下投放广告时,您还必须 为对象检测器任务提供输入帧的时间戳。
  • 在图片模型或视频模型中运行时,对象检测器任务将 阻塞当前线程,直到它处理完输入图像,或者 帧。
  • 在直播模式下运行时,对象检测器任务不会阻塞 当前线程,但会立即返回。它将调用其结果 并在每次处理完一个监听器后将带有检测结果的监听器 输入帧。如果在执行对象检测器任务时调用了检测函数, 系统正忙于处理另一帧,系统会忽略新的输入帧。

处理和显示结果

运行推理时,“对象检测器”任务会返回一个 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

下图直观显示了任务输出:

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