画像分類器を統合する

画像分類は、画像分類でよく使われる、 説明します。たとえば、どのような種類の動物が現れるかを わかります。画像が表すものを予測するタスクは、 画像分類画像分類器は、さまざまな画像、 作成します。たとえば、写真を認識するようにモデルをトレーニングし、 ウサギ、ハムスター、犬の 3 種類の動物を表す画像。詳しくは、 画像分類の例 をご覧ください。

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

ImageClassifier API の主な機能

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

  • 入力画像の関心領域。

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

  • 結果をフィルタするためのスコアしきい値。

  • トップ K の分類結果。

  • ラベルの許可リストと拒否リスト。

サポートされている画像分類モデル

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

Java で推論を実行する

詳しくは、 画像分類リファレンス アプリ をご覧ください。ImageClassifier

ステップ 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
ImageClassifierOptions options =
    ImageClassifierOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setMaxResults(1)
        .build();
ImageClassifier imageClassifier =
    ImageClassifier.createFromFileAndOptions(
        context, modelFile, options);

// Run inference
List<Classifications> results = imageClassifier.classify(image);

詳しくは、 ソースコードと javadoc ImageClassifier を構成するその他のオプションをご覧ください。

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: "birds_V1",
                                            ofType: "tflite") else { return }

let options = ImageClassifierOptions(modelPath: modelPath)

// Configure any additional options:
// options.classificationOptions.maxResults = 3

let classifier = try ImageClassifier.classifier(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: "sparrow.jpg"), let mlImage = MLImage(image: image) else { return }

// Run inference
let classificationResults = try classifier.classify(mlImage: mlImage)

Objective-C

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

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

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

// Configure any additional options:
// options.classificationOptions.maxResults = 3;

TFLImageClassifier *classifier = [TFLImageClassifier imageClassifierWithOptions:options
                                                                          error:nil];

// Convert the input image to MLImage.
UIImage *image = [UIImage imageNamed:@"sparrow.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
TFLClassificationResult *classificationResult =
    [classifier classifyWithGMLImage:gmlImage error:nil];

詳しくは、 ソースコード TFLImageClassifier を構成するその他のオプションをご覧ください。

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)
classification_options = processor.ClassificationOptions(max_results=2)
options = vision.ImageClassifierOptions(base_options=base_options, classification_options=classification_options)
classifier = vision.ImageClassifier.create_from_options(options)

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

# Run inference
image = vision.TensorImage.create_from_file(image_path)
classification_result = classifier.classify(image)

詳しくは、 ソースコード ImageClassifier を構成するその他のオプションをご覧ください。

C++ で推論を実行する

// Initialization
ImageClassifierOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<ImageClassifier> image_classifier = ImageClassifier::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 ClassificationResult result = image_classifier->Classify(*frame_buffer).value();

詳しくは、 ソースコード ImageClassifier を構成するその他のオプションをご覧ください。

検索結果の例

この例は、特定の単語の分類結果を示しています。 鳥の分類器

スズメ

Results:
  Rank #0:
   index       : 671
   score       : 0.91406
   class name  : /m/01bwb9
   display name: Passer domesticus
  Rank #1:
   index       : 670
   score       : 0.00391
   class name  : /m/01bwbt
   display name: Passer montanus
  Rank #2:
   index       : 495
   score       : 0.00391
   class name  : /m/0bwm6m
   display name: Passer italiae

シンプルな ImageClassifier の CLI デモツール 独自のモデルとテストデータで トレーニングできます

モデルの互換性要件

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

    • N クラスと 2 つまたは 4 つのディメンション([1 x N] または [1 x 1 x 1 x N])付き
    • オプション(推奨)タイプで AssociatedFile-s としてマップにラベルを付けます。 TENSOR_AXIS_LABELS には、1 行に 1 つのラベルが含まれます。詳しくは、 サンプル ラベルファイルをご覧ください。 最初の AssociatedFile(存在する場合)が label フィールドに入力されます。 (C++ では class_name と呼ばれます)。display_name フィールド ロケールが一致している AssociatedFile(存在する場合)から 次で使用される ImageClassifierOptionsdisplay_names_locale フィールド 作成日時(デフォルトでは「en」、つまり英語)。上記のいずれも該当しない場合 結果の index フィールドのみが入力されます。