Python 適用的手勢辨識指南

MediaPipe 手勢辨識工作可讓您即時辨識手勢、提供已辨識的手勢結果,以及偵測到的手部的手勢。以下操作說明將說明如何將手勢辨識工具與 Python 應用程式搭配使用。

如要查看這項工作的實際運作情形,請參閱網路示範。如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽

程式碼範例

手勢辨識工具的範例程式碼提供此工作在 Python 中的完整實作,供您參考。這段程式碼可協助您測試這項工作,並開始建構自己的手勢辨識工具。只要使用網路瀏覽器,您就可以查看、執行及編輯手勢辨識工具範例程式碼

如果要實作 Raspberry Pi 的手勢辨識工具,請參閱 Raspberry Pi 範例應用程式

設定

本節說明設定開發環境的重要步驟,以及專門用於手勢辨識工具的程式碼專案。如需瞭解如何使用 MediaPipe 工作設定開發環境的一般資訊,包括平台版本需求,請參閱 Python 設定指南

套裝組合

MediaPipe 手勢辨識工作需要 mediapipe PyPI 套件。您可以透過下列程式碼安裝並匯入這些依附元件:

$ 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/gesture_recognizer.task'

在「模型名稱」參數中指定模型的路徑,如下所示:

base_options = BaseOptions(model_asset_path=model_path)

建立工作

MediaPipe 手勢辨識工作會使用 create_from_options 函式設定工作。create_from_options 函式可接受設定選項值來處理。如要進一步瞭解設定選項,請參閱「設定選項」一文。

下列程式碼示範如何建構及設定這項工作。

這些範例也會顯示圖片、影片檔案和即時影片串流的工作建構變化。

圖片

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
GestureRecognizer = mp.tasks.vision.GestureRecognizer
GestureRecognizerOptions = mp.tasks.vision.GestureRecognizerOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a gesture recognizer instance with the image mode:
options = GestureRecognizerOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.IMAGE)
with GestureRecognizer.create_from_options(options) as recognizer:
  # The detector is initialized. Use it here.
  # ...
    

影片

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
GestureRecognizer = mp.tasks.vision.GestureRecognizer
GestureRecognizerOptions = mp.tasks.vision.GestureRecognizerOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a gesture recognizer instance with the video mode:
options = GestureRecognizerOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.VIDEO)
with GestureRecognizer.create_from_options(options) as recognizer:
  # The detector is initialized. Use it here.
  # ...
    

直播

import mediapipe as mp

BaseOptions = mp.tasks.BaseOptions
GestureRecognizer = mp.tasks.vision.GestureRecognizer
GestureRecognizerOptions = mp.tasks.vision.GestureRecognizerOptions
GestureRecognizerResult = mp.tasks.vision.GestureRecognizerResult
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a gesture recognizer instance with the live stream mode:
def print_result(result: GestureRecognizerResult, output_image: mp.Image, timestamp_ms: int):
    print('gesture recognition result: {}'.format(result))

options = GestureRecognizerOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.LIVE_STREAM,
    result_callback=print_result)
with GestureRecognizer.create_from_options(options) as recognizer:
  # The detector is initialized. Use it here.
  # ...
    

設定選項

這項工作的 Python 應用程式設定選項如下:

選項名稱 說明 值範圍 預設值
running_mode 設定工作的執行模式。共有三種模式:

IMAGE:單一圖片輸入的模式。

影片:影片已解碼影格的模式。

LIVE_STREAM:輸入資料串流 (例如攝影機) 的直播模式。在這個模式下,必須呼叫 resultListener 才能設定事件監聽器,以非同步方式接收結果。
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
num_hands GestureRecognizer 可以偵測出手的數量上限。 Any integer > 0 1
min_hand_detection_confidence 在手掌偵測模型中,系統判定手部偵測成功的最低信心分數。 0.0 - 1.0 0.5
min_hand_presence_confidence 在手部地標偵測模型中,手持狀態分數的最低可信度分數。在影片模式和手勢辨識的直播模式中,如果手部地標模型的手持信心分數低於這個門檻,就會觸發手掌偵測模型。否則,系統會使用輕量的手追蹤演算法判斷手部位置,以便進行後續地標偵測。 0.0 - 1.0 0.5
min_tracking_confidence 系統判定手機追蹤成功時的最低可信度分數。這是目前影格和最後一個影格之間的定界框 IoU 門檻。在影片模式和手勢辨識的串流模式下,如果追蹤失敗,手勢辨識工具會觸發手部偵測。否則系統會略過手部偵測。 0.0 - 1.0 0.5
canned_gestures_classifier_options 設定罐頭手勢分類器行為的選項。罐頭手勢為 ["None", "Closed_Fist", "Open_Palm", "Pointing_Up", "Thumb_Down", "Thumb_Up", "Victory", "ILoveYou"]
  • 顯示名稱語言代碼:透過 TFLite 模型中繼資料指定的顯示名稱 (如有)。
  • 結果數量上限:要傳回的最高分數分類結果數量上限。如果小於 0,系統會傳回所有可用的結果。
  • 分數門檻:分數遭到拒絕的分數,如果設為 0,系統會傳回所有可用的結果。
  • 類別許可清單:類別名稱的許可清單。如果不是空白,系統會篩除不屬於這個組合的分類結果。與拒絕清單互斥。
  • 類別拒絕清單:類別名稱的拒絕清單。如果不是空白,系統會篩除此組合中類別所屬的分類結果。允許與許可清單互斥。
    • 顯示名稱語言代碼:any string
    • 結果數量上限:any integer
    • 分數門檻:0.0-1.0
    • 類別許可清單:vector of strings
    • 類別拒絕清單:vector of strings
    • 顯示名稱語言代碼:"en"
    • 結果數量上限:-1
    • 分數門檻:0
    • 類別許可清單:空白
    • 類別拒絕清單:空白
    custom_gestures_classifier_options 設定自訂手勢分類器行為的選項。
  • 顯示名稱語言代碼:透過 TFLite 模型中繼資料指定的顯示名稱 (如有)。
  • 結果數量上限:要傳回的最高分數分類結果數量上限。如果小於 0,系統會傳回所有可用的結果。
  • 分數門檻:分數遭到拒絕的分數,如果設為 0,系統會傳回所有可用的結果。
  • 類別許可清單:類別名稱的許可清單。如果不是空白,系統會篩除不屬於這個組合的分類結果。與拒絕清單互斥。
  • 類別拒絕清單:類別名稱的拒絕清單。如果不是空白,系統會篩除此組合中類別所屬的分類結果。允許與許可清單互斥。
    • 顯示名稱語言代碼:any string
    • 結果數量上限:any integer
    • 分數門檻:0.0-1.0
    • 類別許可清單:vector of strings
    • 類別拒絕清單:vector of strings
    • 顯示名稱語言代碼:"en"
    • 結果數量上限:-1
    • 分數門檻:0
    • 類別許可清單:空白
    • 類別拒絕清單:空白
    result_callback 設定結果事件監聽器,在手勢辨識工具處於直播模式時,以非同步方式接收分類結果。只能在執行模式設為 LIVE_STREAM 時使用 ResultListener 不適用 不適用

    準備資料

    將輸入內容準備為圖片檔或 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)
        

    執行工作

    手勢辨識工具會使用 cogni、cogni_for_video 和 cogni_async 函式來觸發推論。針對手勢辨識作業,這包括預先處理輸入資料、偵測圖片中的手、偵測手勢地標,以及辨識地標的手勢。

    下列程式碼示範如何使用工作模型執行處理作業。

    圖片

    # Perform gesture recognition on the provided single image.
    # The gesture recognizer must be created with the image mode.
    gesture_recognition_result = recognizer.recognize(mp_image)
        

    影片

    # Perform gesture recognition on the provided single image.
    # The gesture recognizer must be created with the video mode.
    gesture_recognition_result = recognizer.recognize_for_video(mp_image, frame_timestamp_ms)
        

    直播

    # Send live image data to perform gesture recognition.
    # The results are accessible via the `result_callback` provided in
    # the `GestureRecognizerOptions` object.
    # The gesture recognizer must be created with the live stream mode.
    recognizer.recognize_async(mp_image, frame_timestamp_ms)
        

    注意事項:

    • 在影片模式或直播模式中執行時,您也必須為手勢辨識工作提供輸入影格的時間戳記。
    • 在圖片或影片模型中執行時,手勢辨識工作會封鎖目前的執行緒,直到完成輸入圖片或影格的處理為止。
    • 以直播模式執行時,手勢辨識工作不會封鎖目前的執行緒,但會立即傳回。每當完成輸入影格處理作業時,就會透過辨識結果叫用結果事件監聽器。如果手勢辨識工具工作忙於處理其他影格時呼叫辨識函式,則任務會忽略新的輸入框。

    如需在圖片上執行手勢辨識工具的完整範例,請參閱程式碼範例

    處理並顯示結果

    手勢辨識工具會為每個辨識執行作業產生手勢偵測結果物件。結果物件包含圖片座標中的手繪地標、世界座標的手部地標、慣用手(左/右手),以及偵測到的手部手勢類別。

    以下為這項工作的輸出資料範例:

    產生的 GestureRecognizerResult 包含四個元件,每個元件都是陣列,其中每個元素都包含偵測到的一隻手的結果。

    • 慣用手設計

      慣用手是指偵測到的手是左手還是右手。

    • 手勢

      偵測到的手所辨識的手勢類別。

    • 地標

      有 21 個手部地標,每個地標由 xyz 座標組成。xy 座標會分別根據圖片寬度和高度正規化為 [0.0, 1.0]。z 座標代表地標深度,手腕的深度為起點。值越小,地標與相機越近。z 的規模與 x 大致相同。

    • 世界著名地標

      21 隻手的地標也會顯示在世界座標中。每個地標都由 xyz 組成,代表實際的 3D 座標 (以公尺為單位),其起點位於手的幾何中心。

    GestureRecognizerResult:
      Handedness:
        Categories #0:
          index        : 0
          score        : 0.98396
          categoryName : Left
      Gestures:
        Categories #0:
          score        : 0.76893
          categoryName : Thumb_Up
      Landmarks:
        Landmark #0:
          x            : 0.638852
          y            : 0.671197
          z            : -3.41E-7
        Landmark #1:
          x            : 0.634599
          y            : 0.536441
          z            : -0.06984
        ... (21 landmarks for a hand)
      WorldLandmarks:
        Landmark #0:
          x            : 0.067485
          y            : 0.031084
          z            : 0.055223
        Landmark #1:
          x            : 0.063209
          y            : -0.00382
          z            : 0.020920
        ... (21 world landmarks for a hand)
    

    下圖以視覺化方式呈現工作輸出:

    手勢辨識工具範例程式碼示範如何顯示從工作傳回的辨識結果,詳情請參閱程式碼範例