整合圖片區隔工具

圖片區隔工具會預測圖片的每個像素 特定類別與物件偵測相反的是 矩形區域和圖片分類模型則能將整體模型分類 圖片。請參閱圖片區隔總覽 示例 想進一步瞭解圖片區隔工具

使用工作程式庫 ImageSegmenter API 部署自訂圖片區隔器 或是在行動應用程式中預先訓練

ImageSegmenter API 的主要功能

  • 輸入圖片處理作業,包括旋轉、調整大小和色域 轉換率

  • 標籤對應語言代碼。

  • 兩種輸出類型:類別遮罩和可信度遮罩。

  • 供顯示用途的彩色標籤。

支援的圖片分段模型

下列型號保證與 ImageSegmenter 相容 也能使用 Google Cloud CLI 或 Compute Engine API

在 Java 中執行推論

請參閱圖片區隔參考資料 應用程式 查看範例,瞭解如何在 Android 應用程式中使用 ImageSegmenter

步驟 1:匯入 Gradle 依附元件和其他設定

.tflite 模型檔案複製到 Android 模組的資產目錄 以便訓練模型指定不要壓縮檔案,且 將 TensorFlow Lite 程式庫新增至模組的 build.gradle 檔案:

android {
    // Other settings

    // Specify tflite file should not be compressed for the app apk
    aaptOptions {
        noCompress "tflite"
    }
}

dependencies {
    // Other dependencies

    // Import the Task Vision Library dependency
    implementation 'org.tensorflow:tensorflow-lite-task-vision'
    // Import the GPU delegate plugin Library for GPU inference
    implementation 'org.tensorflow:tensorflow-lite-gpu-delegate-plugin'
}

步驟 2:使用模型

// Initialization
ImageSegmenterOptions options =
    ImageSegmenterOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setOutputType(OutputType.CONFIDENCE_MASK)
        .build();
ImageSegmenter imageSegmenter =
    ImageSegmenter.createFromFileAndOptions(context, modelFile, options);

// Run inference
List<Segmentation> results = imageSegmenter.segment(image);

請參閱原始碼並 Javadoc 取得更多設定 ImageSegmenter 的選項。

在 iOS 中執行推論

步驟 1:安裝依附元件

工作程式庫支援使用 CocoaPods 進行安裝。確認 CocoaPods 會在您的系統上安裝。請參閱 CocoaPods 安裝 指南 一文。

請參閱 CocoaPods 指南。 將 Pod 新增至 Xcode 專案

在 Podfile 中新增 TensorFlowLiteTaskVision Pod。

target 'MyAppWithTaskAPI' do
  use_frameworks!
  pod 'TensorFlowLiteTaskVision'
end

確認您要用於推論的 .tflite 模型出現在 您的應用程式套件。

步驟 2:使用模型

Swift

// Imports
import TensorFlowLiteTaskVision

// Initialization
guard let modelPath = Bundle.main.path(forResource: "deeplabv3",
                                            ofType: "tflite") else { return }

let options = ImageSegmenterOptions(modelPath: modelPath)

// Configure any additional options:
// options.outputType = OutputType.confidenceMasks

let segmenter = try ImageSegmenter.segmenter(options: options)

// Convert the input image to MLImage.
// There are other sources for MLImage. For more details, please see:
// https://developers.google.com/ml-kit/reference/ios/mlimage/api/reference/Classes/GMLImage
guard let image = UIImage (named: "plane.jpg"), let mlImage = MLImage(image: image) else { return }

// Run inference
let segmentationResult = try segmenter.segment(mlImage: mlImage)

Objective-C

// Imports
#import <TensorFlowLiteTaskVision/TensorFlowLiteTaskVision.h>

// Initialization
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"deeplabv3" ofType:@"tflite"];

TFLImageSegmenterOptions *options =
    [[TFLImageSegmenterOptions alloc] initWithModelPath:modelPath];

// Configure any additional options:
// options.outputType = TFLOutputTypeConfidenceMasks;

TFLImageSegmenter *segmenter = [TFLImageSegmenter imageSegmenterWithOptions:options
                                                                      error:nil];

// Convert the input image to MLImage.
UIImage *image = [UIImage imageNamed:@"plane.jpg"];

// There are other sources for GMLImage. For more details, please see:
// https://developers.google.com/ml-kit/reference/ios/mlimage/api/reference/Classes/GMLImage
GMLImage *gmlImage = [[GMLImage alloc] initWithImage:image];

// Run inference
TFLSegmentationResult *segmentationResult =
    [segmenter segmentWithGMLImage:gmlImage error:nil];

請參閱原始碼 程式碼 取得更多設定 TFLImageSegmenter 的選項。

在 Python 中執行推論

步驟 1:安裝 pip 套件

pip install tflite-support

步驟 2:使用模型

# Imports
from tflite_support.task import vision
from tflite_support.task import core
from tflite_support.task import processor

# Initialization
base_options = core.BaseOptions(file_name=model_path)
segmentation_options = processor.SegmentationOptions(
    output_type=processor.SegmentationOptions.output_type.CATEGORY_MASK)
options = vision.ImageSegmenterOptions(base_options=base_options, segmentation_options=segmentation_options)
segmenter = vision.ImageSegmenter.create_from_options(options)

# Alternatively, you can create an image segmenter in the following manner:
# segmenter = vision.ImageSegmenter.create_from_file(model_path)

# Run inference
image_file = vision.TensorImage.create_from_file(image_path)
segmentation_result = segmenter.segment(image_file)

請參閱原始碼 程式碼 取得更多設定 ImageSegmenter 的選項。

在 C++ 中執行推論

// Initialization
ImageSegmenterOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<ImageSegmenter> image_segmenter = ImageSegmenter::CreateFromOptions(options).value();

// Create input frame_buffer from your inputs, `image_data` and `image_dimension`.
// See more information here: tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h
std::unique_ptr<FrameBuffer> frame_buffer = CreateFromRgbRawBuffer(
      image_data, image_dimension);

// Run inference
const SegmentationResult result = image_segmenter->Segment(*frame_buffer).value();

請參閱原始碼 程式碼 取得更多設定 ImageSegmenter 的選項。

搜尋結果範例

這個例子是區隔管道的區隔結果 deeplab_v3 TensorFlow Hub 上可用的一般區隔模型

搭飛機

Color Legend:
 (r: 000, g: 000, b: 000):
  index       : 0
  class name  : background
 (r: 128, g: 000, b: 000):
  index       : 1
  class name  : aeroplane

# (omitting multiple lines for conciseness) ...

 (r: 128, g: 192, b: 000):
  index       : 19
  class name  : train
 (r: 000, g: 064, b: 128):
  index       : 20
  class name  : tv
Tip: use a color picker on the output PNG file to inspect the output mask with
this legend.

區隔類別遮罩看起來應像這樣:

segmentation-output

試用簡單的 CLI 示範工具, ImageSegmenter 使用自己的模型與測試資料

模型相容性需求

ImageSegmenter API 預期的 TFLite 模型須搭配必要的 TFLite 模型 中繼資料。查看建立映像檔中繼資料的範例 使用 TensorFlow Lite 中繼資料寫入器 API

  • 輸入圖片張量 (kTfLiteUInt8/kTfLiteFloat32)

    • 輸入大小為 [batch x height x width x channels] 的圖片。
    • 不支援批次推論 (batch 須為 1)。
    • 僅支援 RGB 輸入 (channels 必須為 3)。
    • 如果型別是 kTfLiteFloat32,就必須使用正規化選項 附加於中繼資料,以便進行輸入正規化
  • 輸出遮罩張量:(kTfLiteUInt8/kTfLiteFloat32)

    • 大小為 [batch x mask_height x mask_width x num_classes] 的張量,其中 batch 必須是 1,mask_widthmask_height 是 模型產生的區隔遮罩維度,以及 num_classes 是模型支援的類別數量。
    • (但建議使用) 標籤對應,可以將 與 TENSOR_AXIS_LABELS 類型的 AssociatedFile-s 和 TENSOR_AXIS_LABELS 類型,各包含一個標籤 互動第一個這類 AssociatedFile (如有) 會填入 label 欄位 (在 C++ 中稱為 class_name)。display_name 欄位將填入關聯檔案 (如有),且語言代碼符合 使用的 ImageSegmenterOptionsdisplay_names_locale 欄位 建立時間 (預設為「en」,例如英文)。如果這些都不是 可用,只有結果的 index 欄位會填入內容。