画像セグメンタを統合する

画像セグメンタは、画像の各ピクセルが特定の画像に関連付けられたかどうかを 作成します。これとは異なり、オブジェクト検出では、 画像分類という 2 つの方法が用意されており、 説明します。画像セグメンテーションの概要をご覧ください。 例 をご覧ください。

タスク ライブラリの ImageSegmenter API を使用してカスタム イメージ セグメンタをデプロイする モバイルアプリに取り込むことができます

ImageSegmenter API の主な機能

  • 入力画像処理(回転、サイズ変更、色空間など) なります。

  • 地図の言語 / 地域にラベルを付けます。

  • カテゴリマスクと信頼度マスクの 2 つの出力タイプ。

  • 表示用の色付きのラベル。

サポートされている画像セグメンタ モデル

次のモデルは、ImageSegmenter との互換性が保証されています API

Java で推論を実行する

詳しくは、画像セグメンテーションのリファレンス アプリ をご覧ください。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 が Cloud Shell で がインストールされていることを確認できます。詳しくは、CocoaPods のインストールに関するページ ガイド をご覧ください。

詳しくは、CocoaPods ガイドを参照し、 Xcode プロジェクトに Pod を追加します。

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 Metadata Writer を使用したセグメンタ API

  • 入力画像のテンソル(kTfLiteUInt8/kTfLiteFloat32)

    • サイズ [batch x height x width x channels] の画像入力。
    • バッチ推論はサポートされていません(batch は 1 にする必要があります)。
    • RGB 入力のみがサポートされます(channels は 3 にする必要があります)。
    • 型が kTfLiteFloat32 の場合、NormalizationOptions は必須です。 メタデータにアタッチされるデータです。
  • 出力マスクのテンソル:(kTfLiteUInt8/kTfLiteFloat32)

    • サイズが [batch x mask_height x mask_width x num_classes] のテンソル。 batch は 1 にする必要があります。mask_widthmask_height は モデルによって生成されたセグメンテーション マスクのディメンション、 num_classes は、モデルでサポートされているクラスの数です。
    • オプション(推奨)のラベルマップは、 タイプ TENSOR_AXIS_LABELS の AssociatedFile-s には、タイプごとに 1 つのラベルが含まれます 追加します。最初の AssociatedFile(存在する場合)が、label に入力されます。 フィールド(C++ では class_name)になります。display_name フィールドは、ロケールが 次で使用される ImageSegmenterOptionsdisplay_names_locale フィールド 作成日時(デフォルトでは「en」、つまり英語)。上記のいずれも該当しない場合 結果の index フィールドのみが入力されます。