Python 適用的圖片區隔指南

MediaPipe 圖片區隔工作可讓您根據預先定義的類別,將圖片分為不同的區域,以便套用背景模糊效果等視覺效果。以下操作說明為您示範如何搭配 Python 語言使用圖片區隔。如要進一步瞭解這項工作的功能、模型和設定選項,請參閱總覽

程式碼範例

圖片區隔的範例程式碼提供此工作在 Python 中的完整實作,供您參考。這段程式碼可協助您測試這項工作,並開始建構自己的圖片區隔應用程式。只要使用網路瀏覽器,您就可以查看、執行及修改 Image Segmenter 範例程式碼

設定

本節說明設定開發環境及專門為使用 Image Segmenter 的程式碼專案的重要步驟。如需瞭解如何使用 MediaPipe 工作設定開發環境的一般資訊,包括平台版本需求,請參閱 Python 設定指南。您可以前往 GitHub 查看本範例的原始碼。

套裝組合

MediaPipe 圖片區隔工作需要 mediapipe 套件。您可以使用下列指令安裝必要的依附元件:

$ 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/model.tflite'

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

base_options = BaseOptions(model_asset_path=model_path)

建立工作

MediaPipe 圖片區隔工作會使用 create_from_options 函式設定工作。create_from_options 函式可接受設定選項值來處理。如要進一步瞭解工作設定,請參閱設定選項一文。

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

圖片

BaseOptions = mp.tasks.BaseOptions
ImageSegmenter = mp.tasks.vision.ImageSegmenter
ImageSegmenterOptions = mp.tasks.vision.ImageSegmenterOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a image segmenter instance with the image mode:
options = ImageSegmenterOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.IMAGE,
    output_category_mask=True)
with ImageSegmenter.create_from_options(options) as segmenter:
  

影片

BaseOptions = mp.tasks.BaseOptions
ImageSegmenter = mp.tasks.vision.ImageSegmenter
ImageSegmenterOptions = mp.tasks.vision.ImageSegmenterOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a image segmenter instance with the video mode:
options = ImageSegmenterOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.VIDEO,
    output_category_mask=True)
with ImageSegmenter.create_from_options(options) as segmenter:
  

直播

BaseOptions = mp.tasks.BaseOptions
ImageSegmenter = mp.tasks.vision.ImageSegmenter
ImageSegmenterOptions = mp.tasks.vision.ImageSegmenterOptions
VisionRunningMode = mp.tasks.vision.RunningMode

# Create a image segmenter instance with the live stream mode:
def print_result(result: List[Image], output_image: Image, timestamp_ms: int):
    print('segmented masks size: {}'.format(len(result)))

options = ImageSegmenterOptions(
    base_options=BaseOptions(model_asset_path='/path/to/model.task'),
    running_mode=VisionRunningMode.VIDEO,
    output_category_mask=True)
with ImageSegmenter.create_from_options(options) as segmenter:
    

設定選項

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

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

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

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

LIVE_STREAM:輸入資料串流 (例如攝影機) 的直播模式。在這個模式下,必須呼叫 resultListener 才能設定事件監聽器,以非同步方式接收結果。
{IMAGE, VIDEO, LIVE_STREAM} IMAGE
output_category_mask 如果設為 True,輸出結果會包含 uint8 圖片的區隔遮罩,其中每個像素值都代表勝出類別值。 {True, False} False
output_confidence_masks 如果設為 True,輸出結果會包含以浮點值圖片形式的區隔遮罩,其中每個浮點值都代表該類別的可信度分數對應關係。 {True, False} True
display_names_locale 設定標籤語言,用於工作模型中繼資料內的顯示名稱 (如有)。英文的預設值是 en。您可以使用 TensorFlow Lite Metadata Writer API,在自訂模型的中繼資料中加入本地化標籤。語言代碼 en
result_callback 在圖片區隔處於直播模式時,設定結果監聽器以非同步方式接收區隔結果。只能在執行模式設為 LIVE_STREAM 時使用 不適用 不適用

準備資料

將輸入準備為圖片檔或 numpy 陣列,然後再將其轉換為 mediapipe.Image 物件。如果輸入的內容是影片檔案,或是透過網路攝影機直播,可以使用外部程式庫 (例如 OpenCV) 將輸入影格載入為 numpy 陣列。

圖片

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

影片

# Use OpenCV’s VideoCapture to load the input video.
# Load the frame rate of the video using OpenCV’s CV_CAP_PROP_FPS
# You need the frame rate 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)
    

直播

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

如需圖片區隔資料準備工作的程式碼範例,請參閱程式碼範例

執行工作

圖片區隔會使用 segmentsegment_for_videosegment_async 函式來觸發推論。針對圖片區隔,這包括預先處理輸入資料、執行區隔模型,以及對已分割遮罩的原始模型輸出進行後續處理。

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

圖片

# Perform image segmentation on the provided single image.
# The image segmenter must be created with the image mode.
segmented_masks = segmenter.segment(mp_image)
    

影片

# Perform image segmentation on the provided single image.
# The image segmenter must be created with the video mode.
segmented_masks = segmenter.segment_for_video(mp_image, frame_timestamp_ms)
    

直播

# Send live image data to perform image segmentation.
# The results are accessible via the `result_callback` provided in
# the `ImageSegmenterOptions` object.
# The image segmenter must be created with the live stream mode.
segmenter.segment_async(mp_image, frame_timestamp_ms)
    

注意事項:

  • 以影片模式或直播模式執行時,您還必須為圖片區隔工作提供輸入影格的時間戳記。
  • 在圖片或影片模型中執行時,「圖片區隔」工作會封鎖目前的執行緒,直到完成輸入圖片或影格的處理為止。

如需執行圖片區隔推論的完整範例,請參閱程式碼範例

處理並顯示結果

圖片區隔會輸出 Image 資料清單。如果 output_typeCATEGORY_MASK,則會輸出清單,其中包含單一區隔遮罩做為 uint8 映像檔。像素代表輸入圖片的可識別類別索引。如果 output_typeCONFIDENCE_MASK,輸出結果就會是類別數值大小的向量。每個區隔遮罩都是 [0,1] 範圍內的浮點圖片,代表該類別中像素的可信度分數。

以下各節說明這項工作的輸出資料範例:

類別可信度

下圖顯示類別可信度遮罩的工作輸出內容。可信度遮罩輸出包含介於 [0, 1] 之間的浮點值。

原始圖片和類別可信度遮罩輸出內容。Pascal VOC 2012 資料集的來源映像檔。

類別值

下圖以視覺化方式呈現類別值遮罩的工作輸出內容。類別遮罩範圍為 [0, 255],每個像素值代表模型輸出的勝出類別索引。勝出類別索引是模型可識別類別中的最高分數。

原始圖片和類別遮罩輸出內容。Pascal VOC 2012 資料集的來源映像檔。