Python 適用的圖片分類指南

MediaPipe 圖片分類器工作可讓您對圖片進行分類。您可以使用這項工作,在訓練期間定義的一組類別中,找出圖片代表的內容。本操作說明說明如何使用 Python 使用圖像分類器。

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

程式碼範例

圖像分類器的範例程式碼提供了 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 種輸入資料類型:靜態圖片、影片檔案和即時影片串流。請選擇對應於輸入資料類型的分頁,瞭解如何建立工作並執行推論。

圖片

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.
  # ...
    

如需建立 Image Classifier 以搭配圖片使用的完整範例,請參閱程式碼範例

設定選項

此工作包含下列 Python 應用程式的設定選項:

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

IMAGE:單一圖片輸入模式。

VIDEO:影片解碼影格模式。

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 在 Image Classifier 處於即時串流模式時,將結果事件監聽器設為以非同步方式接收分類結果。只有在執行模式設為 LIVE_STREAM 時,才能使用 不適用 未設定

準備資料

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

執行工作

您可以呼叫對應於執行模式的 classify 函式,觸發推論。Image Classifier API 會傳回輸入圖片或影格中物件的可能類別。

圖片

# 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 函式,工作會忽略新的輸入影格。

如需建立 Image Classifier 以搭配圖片使用的完整範例,請參閱程式碼範例

處理及顯示結果

執行推論時,圖片分類器工作會傳回 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

這項結果是透過以下方式取得:在以下裝置上執行鳥類分類器

斑文鳥特寫相片

圖像分類器範例程式碼示範如何顯示工作傳回的分類結果,詳情請參閱程式碼範例