オブジェクト検出を統合する

オブジェクト検出機能を使用すると、既知のオブジェクトのセットを識別できます。 特定の画像または動画内での位置に関する情報の提供 。オブジェクト検出機能は、オブジェクトの存在と位置情報を検出するようにトレーニングされています。 オブジェクトの複数のクラスを作成できます。たとえば、モデルに画像を使用してトレーニングすると、 (さまざまな果物を含む)と、そのフルーツを指定するラベル 果物の種類(例: リンゴ、バナナ、イチゴ) 各オブジェクトが画像内のどこに表示されるかを指定するデータです。詳しくは、 オブジェクト検出の例 をご覧ください。

タスク ライブラリ ObjectDetector API を使用してカスタム オブジェクト検出機能をデプロイする モバイルアプリに取り込むことができます

ObjectDetector API の主な機能

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

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

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

  • トップ K の検出結果。

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

サポートされているオブジェクト検出モデル

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

Java で推論を実行する

詳しくは、 オブジェクト検出リファレンス アプリ をご覧ください。ObjectDetector

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

// Run inference
List<Detection> results = objectDetector.detect(image);

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

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

let options = ObjectDetectorOptions(modelPath: modelPath)

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

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

// Run inference
let detectionResult = try detector.detect(mlImage: mlImage)

Objective-C

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

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

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

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

TFLObjectDetector *detector = [TFLObjectDetector objectDetectorWithOptions:options
                                                                     error:nil];

// Convert the input image to MLImage.
UIImage *image = [UIImage imageNamed:@"dogs.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
TFLDetectionResult *detectionResult = [detector detectWithGMLImage:gmlImage error:nil];

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

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)
detection_options = processor.DetectionOptions(max_results=2)
options = vision.ObjectDetectorOptions(base_options=base_options, detection_options=detection_options)
detector = vision.ObjectDetector.create_from_options(options)

# Alternatively, you can create an object detector in the following manner:
# detector = vision.ObjectDetector.create_from_file(model_path)

# Run inference
image = vision.TensorImage.create_from_file(image_path)
detection_result = detector.detect(image)

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

C++ で推論を実行する

// Initialization
ObjectDetectorOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<ObjectDetector> object_detector = ObjectDetector::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 DetectionResult result = object_detector->Detect(*frame_buffer).value();

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

検索結果の例

このスライドは、VM の検出結果に ssd mobilenet v1 TensorFlow Hub から読み込みます。

犬

Results:
 Detection #0 (red):
  Box: (x: 355, y: 133, w: 190, h: 206)
  Top-1 class:
   index       : 17
   score       : 0.73828
   class name  : dog
 Detection #1 (green):
  Box: (x: 103, y: 15, w: 138, h: 369)
  Top-1 class:
   index       : 17
   score       : 0.73047
   class name  : dog

境界ボックスを入力画像にレンダリングします。

検出出力

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

モデルの互換性要件

ObjectDetector API は、必須の TFLite モデルを想定しています。 TFLite モデル メタデータ。作成の例を見る オブジェクト検出用のメタデータを TensorFlow Lite Metadata Writer API

互換性のあるオブジェクト検出モデルは、次の要件を満たす必要があります。

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

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

    • 位置テンソル(kTfLiteFloat32) <ph type="x-smartling-placeholder">
        </ph>
      • サイズ [1 x num_results x 4] のテンソル。内部配列 [top, left, right, bottom] という形式の境界ボックスです。
      • BoundingBoxProperties をメタデータに添付する必要がある type=BOUNDARIES と「vertical_type=RATIO」を指定する必要があります。
    • クラスのテンソル(kTfLiteFloat32)

      • サイズ [1 x num_results] のテンソルで、それぞれの値は クラスの整数インデックス。
      • オプション(推奨)のラベルマップは、 タイプ TENSOR_VALUE_LABELS の AssociatedFile-s に 1 つのラベルが含まれます あります。詳しくは、 サンプル ラベルファイルをご覧ください。 最初の AssociatedFile(存在する場合)は、 結果の class_name フィールド。display_name フィールドは次のようになります。 ロケールが一致している AssociatedFile(存在する場合)から 次で使用される ObjectDetectorOptionsdisplay_names_locale フィールド 作成日時(デフォルトでは「en」、つまり英語)。上記のいずれも該当しない場合 結果の index フィールドのみが入力されます。
    • スコアのテンソル(kTfLiteFloat32)

      • サイズ [1 x num_results] のテンソルで、それぞれの値は オブジェクトのスコアです。
    • 検出テンソルの数(kTfLiteFloat32)

      • 整数 num_results をサイズの [1] のテンソルとして計算します。