MediaPipe 圖片分類器工作可讓您對圖片進行分類。您可以使用這項工作,識別圖片在訓練期間定義的一組類別中代表什麼。這些指示會示範如何搭配使用圖片分類器與 Python。
您可以查看 Web 示範 來瞭解這項工作的實際運作情形。如要進一步瞭解此工作的功能、模型和設定選項,請參閱「總覽」一文。
程式碼範例
圖片分類器的範例程式碼提供這個工作在 Python 中的完整實作,供您參考。這個程式碼可協助您測試這項工作,並開始建構自己的圖片分類器。您可以使用網路瀏覽器查看、執行及編輯圖片分類器程式碼範例。
如果要實作 Raspberry Pi 的 Image Classifier,請參閱 Raspberry Pi 範例應用程式。
設定
本節說明設定開發環境的重要步驟,以及特別使用 Image Classifier 的程式碼專案。如需使用 MediaPipe 工作設定開發環境的一般資訊 (包括平台版本要求),請參閱 Python 設定指南。
套件
Image Classifier 會工作 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 Image Classifier 工作需要與這項工作相容的已訓練模型。如要進一步瞭解圖片分類器可用的已訓練模型,請參閱工作總覽的「模型」一節。
選取並下載模型,然後儲存至本機目錄。您可以使用建議的 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. # ...
如需建立圖片分類器與圖片的完整範例,請參閱程式碼範例。
設定選項
這項工作有下列 Python 應用程式設定選項:
選項名稱 | 說明 | 值範圍 | 預設值 |
---|---|---|---|
running_mode |
設定任務的執行模式。有三種模式: 圖片:單一圖片輸入模式。 影片:影片已解碼影格的模式。 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 |
設定結果事件監聽器,以便在圖片分類器處於直播模式時,以非同步方式接收分類結果。只有在執行模式設為「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)
執行工作
您可以呼叫與執行模式相對應的分類函式來觸發推論。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
函式,該工作會忽略新的輸入影格。
如需建立圖片分類器與圖片的完整範例,請參閱程式碼範例。
處理及顯示結果
執行推論時,圖片分類器工作會傳回 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
以下裝置會執行 Bird Classifier 來取得這個結果:
圖片分類器程式碼範例示範如何顯示工作傳回的分類結果,詳情請參閱程式碼範例。