Python 設定指南

本頁說明如何設定開發環境,在 Python 應用程式中使用 MediaPipe Tasks。

支援的平台和版本

如要使用 MediaPipe Tasks 建構應用程式,需要下列開發環境資源:

  • 作業系統:
    • 電腦:Windows、Mac、Linux
    • IoT:Raspberry OS 64 位元
  • Python:3.9 至 3.12 版
  • PIP:20.3 以上版本

設定開發人員環境

在 Python 應用程式上執行 MediaPipe 工作前,請先安裝 MediaPipe 套件。

$ python -m pip install mediapipe

安裝套件後,請將其匯入開發專案。

import mediapipe as mp

MediaPipe Tasks 依附元件

MediaPipe Tasks 提供三種預建程式庫,分別用於影像、文字和音訊。視應用程式使用的 MediaPipe 工作而定,將影像、文字或音訊程式庫匯入開發專案。

Vision 任務

MediaPipe Tasks 視覺模組包含處理圖片或影片輸入內容的任務。如要匯入 MediaPipe Tasks Vision 程式庫,請將下列依附元件匯入開發專案。

from mediapipe.tasks.python import vision

文字工作

MediaPipe Tasks 文字模組包含處理字串輸入內容的工作。如要匯入 MediaPipe Tasks 文字程式庫,請將下列依附元件匯入開發專案。

from mediapipe.tasks.python import text

音訊工作

MediaPipe Tasks 音訊模組包含處理聲音輸入的任務。如要匯入 MediaPipe Tasks 音訊程式庫,請將下列依附元件匯入開發專案。

from mediapipe.tasks.python import audio

設定 BaseOptions

BaseOptions 可用於 MediaPipe Task API 的一般設定。

選項名稱 說明 接受的值
model_asset_buffer 模型資產檔案內容。 以位元組字串形式呈現模型內容
model_asset_path 要開啟並對應至記憶體的模型資產路徑。 檔案路徑 (字串)

使用 PyInstaller 將 Python Tasks 應用程式封裝

使用 PyInstaller 封裝 Python Tasks 應用程式時,系統不會自動納入模型檔案 (例如 .task 組合包)。如果應用程式使用 BaseOptions(model_asset_path=...),請在 PyInstaller 套件中加入模型檔案,並在執行階段解析其路徑。

舉例來說,使用檢查 PyInstaller sys._MEIPASS 目錄的輔助程式:

import os
import sys

def resource_path(relative_path: str) -> str:
    base_path = getattr(sys, "_MEIPASS", os.path.abspath("."))
    return os.path.join(base_path, relative_path)

然後將已解析的模型路徑傳遞至 BaseOptions

from mediapipe.tasks import python
from mediapipe.tasks.python import vision

model_path = resource_path("pose_landmarker.task")
base_options = python.BaseOptions(model_asset_path=model_path)
options = vision.PoseLandmarkerOptions(base_options=base_options)
pose_landmarker = vision.PoseLandmarker.create_from_options(options)

使用 PyInstaller 建構時,請將模型檔案和 MediaPipe 套件檔案組合在一起:

pyinstaller app.py \
  --add-data "pose_landmarker.task:." \
  --collect-all mediapipe \
  --hidden-import mediapipe.tasks.c

在 macOS 或 Linux 上,--add-data 分隔符號為 :。在 Windows 上,請使用 ;。如果是 macOS 電腦應用程式,請加入 --windowed 來建立 .app 套件:

疑難排解

如有 MediaPipe 技術問題需要協助,請前往討論群組Stack Overflow,向社群尋求支援。如要回報錯誤或要求功能,請在 GitHub 上提出問題

如需設定 Python 開發環境的說明,請參閱 Python 開發人員指南