MediaPipe 圖片嵌入工具工作可讓您將圖片資料轉換為數字表示法,以完成與機器學習相關的圖片處理工作,例如比較兩張圖片的相似度。以下操作說明將說明如何搭配 Python 使用圖片嵌入工具。
如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽。
程式碼範例
「Image Embedder」的範例程式碼提供此工作在 Python 中的完整實作,供您參考。這個程式碼可協助您測試這項工作,並開始建構自己的圖片嵌入程式。有了 Google Colab,只要使用網路瀏覽器,就能檢視、執行及編輯圖片嵌入程式範例程式碼。您可以前往 GitHub 查看此範例的原始碼。
設定
本節說明設定開發環境的重要步驟,以及專門用來使用 Image Embedder 的程式碼專案。如需瞭解如何使用 MediaPipe 工作設定開發環境的一般資訊,包括平台版本需求,請參閱 Python 設定指南。
套裝組合
Image Embedder 工作是 mediapipe pip 套件。您可以使用以下項目安裝依附元件:
$ python -m pip install mediapipe
匯入
匯入下列類別,即可存取圖片嵌入工具工作函式:
import mediapipe as mp
from mediapipe.tasks import python
from mediapipe.tasks.python import vision
型號
MediaPipe 圖片嵌入程式工作需要與這項工作相容的已訓練模型。如要進一步瞭解圖片嵌入工具的可用已訓練模型,請參閱工作總覽「模型」一節。
選取並下載模型,然後儲存至本機目錄中。您可以使用建議的 MobileNetV3 模型。
model_path = '/absolute/path/to/mobilenet_v3_small_075_224_embedder.tflite'
在 model_asset_path
參數中指定模型的路徑,如下所示:
base_options = BaseOptions(model_asset_path=model_path)
建立工作
您可以使用 create_from_options
函式建立工作。create_from_options
函式可接受設定選項,設定嵌入工具選項。如要進一步瞭解設定選項,請參閱「設定總覽」一文。
圖片嵌入工具工作支援 3 種輸入資料類型:靜態圖片、影片檔案和直播影片串流。選擇與輸入資料類型對應的分頁,瞭解如何建立工作並執行推論。
圖片
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageEmbedder = mp.tasks.vision.ImageEmbedder ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions VisionRunningMode = mp.tasks.vision.RunningMode options = ImageEmbedderOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), quantize=True, running_mode=VisionRunningMode.IMAGE) with ImageEmbedder.create_from_options(options) as embedder: # The embedder is initialized. Use it here. # ...
影片
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageEmbedder = mp.tasks.vision.ImageEmbedder ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions VisionRunningMode = mp.tasks.vision.RunningMode options = ImageEmbedderOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), quantize=True, running_mode=VisionRunningMode.VIDEO) with ImageEmbedder.create_from_options(options) as embedder: # The embedder is initialized. Use it here. # ...
直播
import mediapipe as mp BaseOptions = mp.tasks.BaseOptions ImageEmbedderResult = mp.tasks.vision.ImageEmbedder.ImageEmbedderResult ImageEmbedder = mp.tasks.vision.ImageEmbedder ImageEmbedderOptions = mp.tasks.vision.ImageEmbedderOptions VisionRunningMode = mp.tasks.vision.RunningMode def print_result(result: ImageEmbedderResult, output_image: mp.Image, timestamp_ms: int): print('ImageEmbedderResult result: {}'.format(result)) options = ImageEmbedderOptions( base_options=BaseOptions(model_asset_path='/path/to/model.tflite'), running_mode=VisionRunningMode.LIVE_STREAM, quantize=True, result_callback=print_result) with ImageEmbedder.create_from_options(options) as embedder: # The embedder is initialized. Use it here. # ...
設定選項
這項工作的 Python 應用程式設定選項如下:
選項名稱 | 說明 | 值範圍 | 預設值 |
---|---|---|---|
running_mode |
設定工作的執行模式。共有三種模式: IMAGE:單一圖片輸入的模式。 影片:影片已解碼影格的模式。 LIVE_STREAM:輸入資料串流 (例如攝影機) 的直播模式。在這個模式下,必須呼叫 resultListener 才能設定事件監聽器,以非同步方式接收結果。 |
{IMAGE, VIDEO, LIVE_STREAM } |
IMAGE |
l2_normalize |
是否使用 L2 正規化傳回的特徵向量。只有在模型不含原生 L2_NORMALIZATION TFLite Op 的情況下,才能使用這個選項。在大多數情況下,已經是此情況,L2 正規化是透過 TFLite 推論達成,不需要使用這個選項。 | Boolean |
False |
quantize |
是否應透過純量量化,將傳回的嵌入量化為位元組。以隱含方式假設嵌入為單位標準,因此任何維度保證在 [-1.0, 1.0] 中都有一個值。如果並非如此,請使用 l2_正規化選項。 | Boolean |
False |
result_callback |
在 Image Embedder 處於直播模式時,設定結果事件監聽器以非同步方式接收嵌入結果。只能在執行模式設為 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 Embedder API 會傳回輸入圖片或影格的嵌入向量。
圖片
# Perform image embedding on the provided single image. embedding_result = embedder.embed(mp_image)
影片
# Calculate the timestamp of the current frame frame_timestamp_ms = 1000 * frame_index / video_file_fps # Perform image embedding on the video frame. embedding_result = embedder.embed_for_video(mp_image, frame_timestamp_ms)
直播
# Send the latest frame to perform image embedding. # Results are sent to the `result_callback` provided in the `ImageEmbedderOptions`. embedder.embed_async(mp_image, frame_timestamp_ms)
注意事項:
- 以影片模式或直播模式執行時,您也必須提供圖片嵌入工具工作,顯示輸入影格的時間戳記。
- 在圖片或影片模型中執行時,圖片嵌入程式工作會封鎖目前的執行緒,直到完成輸入圖片或影格的處理為止。
- 以直播模式執行時,圖片嵌入工具工作不會封鎖目前的執行緒,但會立即傳回。每當完成輸入影格處理之後,就會透過嵌入結果叫用結果事件監聽器。如果在圖片嵌入工具工作忙於處理其他影格時呼叫
embedAsync
函式,則工作會忽略新的輸入影格。
處理並顯示結果
執行推論時,Image Embedder 工作會傳回 ImageEmbedderResult
物件,其中包含輸入圖片或影格中物件的可能類別清單。
以下為這項工作的輸出資料範例:
ImageEmbedderResult:
Embedding #0 (sole embedding head):
float_embedding: {0.0, 0.0, ..., 0.0, 1.0, 0.0, 0.0, 2.0}
head_index: 0
這項結果是嵌入以下圖片來取得:
您可以使用 ImageEmbedder.cosine_similarity
函式來比較兩個嵌入的相似性。相關範例請看以下程式碼。
# Compute cosine similarity.
similarity = ImageEmbedder.cosine_similarity(
embedding_result.embeddings[0],
other_embedding_result.embeddings[0])