画像分類タスクを使用すると、画像の分類を実行できます。次を使用: このタスクでは、定義された一連のカテゴリの中から画像が何を表しているかを識別します。 決定できますここでは、Google Chat で画像分類器を使用する方法について説明します。 iOS アプリ。この手順で説明するコードサンプルは、 GitHub。
このタスクの動作を確認するには、こちらのウェブ デモをご覧ください。対象 Google Cloud インフラストラクチャの機能、モデル、構成オプションについて 詳細については、 概要。
サンプルコード
MediaPipe Tasks のサンプルコードは、画像分類器の基本的な実装です。 アプリこの例では、物理的な iOS デバイスのカメラを使用して、 オブジェクトを連続的に分類できます。また、画像と動画を使用して 静的にオブジェクトを分類できます。
独自の iOS アプリの出発点としてアプリを使用することも、アプリ自体に言及することもできます。 変更する際の注意点があります。画像分類器のサンプルコードは GitHub。
コードをダウンロードする
次の手順では、サンプルのローカルコピーを作成する方法を示します。 git コマンドライン ツールを使用してコードを実行します。
<ph type="x-smartling-placeholder">サンプルコードをダウンロードするには:
次のコマンドを使用して Git リポジトリのクローンを作成します。
git clone https://github.com/google-ai-edge/mediapipe-samples
必要に応じて、スパース チェックアウトを使用するように Git インスタンスを構成し、 Image Classifier サンプルアプリのファイルのみを表示します。
cd mediapipe git sparse-checkout init --cone git sparse-checkout set examples/image_classification/ios/
ローカル バージョンのサンプルコードを作成したら、 MediaPipe タスク ライブラリで、Xcode を使用してプロジェクトを開き、アプリを実行します。対象 手順については、iOS の設定ガイドをご覧ください。
主要コンポーネント
次のファイルには、画像分類器の例に不可欠なコードが含まれています。 アプリケーション:
- ImageClassifierService.swift: 画像分類器を初期化し、モデル選択を処理して、入力データに対する推論を実行します。
- CameraViewController.swift: ライブカメラフィード入力モードの UI を実装し、結果を可視化します。
- MediaLibraryViewController.swift 静止画像と動画ファイルの入力モードの UI を実装し、結果を可視化します。
セットアップ
このセクションでは、開発環境をセットアップする主な手順と 画像分類器を使用するコード プロジェクトです設定に関する一般的な情報については、 MediaPipe タスクを使用するための開発環境(プラットフォーム バージョンを含む) iOS の設定ガイドをご覧ください。
<ph type="x-smartling-placeholder">依存関係
画像分類器は MediaPipeTasksVision
ライブラリを使用します。このライブラリは、インストールする必要があります。
構築しましたこのライブラリは Swift アプリと Objective-C アプリの両方と互換性がある
言語固有の追加の設定は不要です
macOS に CocoaPods をインストールする手順については、CocoaPods
インストール ガイドをご覧ください。
必要な Pod を使用して Podfile
を作成する方法については、
詳しくは、
CocoaPods。
次のコードを使用して、Podfile
に MediaPipeTasksVision Pod を追加します。
target 'MyImageClassifierApp' do
use_frameworks!
pod 'MediaPipeTasksVision'
end
アプリに単体テスト ターゲットが含まれている場合は、
iOS をご覧ください。
あなたのPodfile
。
モデル
MediaPipe 画像分類タスクには、互換性のあるトレーニング済みモデルが必要 見ていきましょう。利用可能なトレーニング済みモデルについて詳しくは、 画像分類器については、タスクの概要をご覧ください。モデル セクションをご覧ください。
モデルを選択してダウンロードし、Xcode を使用してプロジェクト ディレクトリに追加します。 Xcode プロジェクトにファイルを追加する方法については、 Xcode 内のファイルとフォルダ プロジェクトです。
BaseOptions.modelAssetPath
プロパティを使用してモデルのパスを指定する
追加できますコード例については、次のセクションをご覧ください。
タスクを作成する
画像分類タスクを作成するには、そのイニシャライザのいずれかを呼び出します。「
ImageClassifier(options:)
イニシャライザが構成オプションの値を設定する
ランニングモード、表示名のロケール、結果の最大数、信頼度を含む
拒否リストなどがあります
カスタマイズされた構成で初期化される画像分類器が不要な場合
ImageClassifier(modelPath:)
イニシャライザを使用して、
デフォルトのオプションを含む画像分類器です。リソースの構成について
構成の概要をご覧ください。
画像分類タスクは、静止画像と動画ファイルの 3 つの入力データ型をサポートします。
ストリーミング動画にも対応していますデフォルトでは、ImageClassifier(modelPath:)
は
行います。動画を処理するためにタスクを初期化する場合は、
使用する場合は、ImageClassifier(options:)
を使用して
配信モードを選択できますライブ配信モードでは、
追加の imageClassifierLiveStreamDelegate
構成オプションがあり、
画像分類器が画像分類の結果を
委任できます。
ランニングモードに対応するタブを選択すると、タスクの作成方法を確認できます 推論を実行できます
Swift
画像
import MediaPipeTasksVision let modelPath = Bundle.main.path(forResource: "model", ofType: "tflite") let options = ImageClassifierOptions() options.baseOptions.modelAssetPath = modelPath options.runningMode = .image options.maxResults = 5 let imageClassifier = try ImageClassifier(options: options)
動画
import MediaPipeTasksVision let modelPath = Bundle.main.path(forResource: "model", ofType: "tflite") let options = ImageClassifierOptions() options.baseOptions.modelAssetPath = modelPath options.runningMode = .video options.maxResults = 5 let imageClassifier = try ImageClassifier(options: options)
ライブ配信
import MediaPipeTasksVision // Class that conforms to the `ImageClassifierLiveStreamDelegate` protocol and // implements the method that the image classifier calls once it // finishes performing classification on each input frame. class ImageClassifierResultProcessor: NSObject, ImageClassifierLiveStreamDelegate { func imageClassifier( _ imageClassifier: ImageClassifier, didFinishClassification result: ImageClassifierResult?, timestampInMilliseconds: Int, error: Error?) { // Process the image classifier result or errors here. } } let modelPath = Bundle.main.path( forResource: "model", ofType: "tflite") let options = ImageClassifierOptions() options.baseOptions.modelAssetPath = modelPath options.runningMode = .liveStream options.maxResults = 5 // Assign an object of the class to the `imageClassifierLiveStreamDelegate` // property. let processor = ImageClassifierResultProcessor() options.imageClassifierLiveStreamDelegate = processor let imageClassifier = try ImageClassifier(options: options)
Objective-C
画像
@import MediaPipeTasksVision; NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"tflite"]; MPPImageClassifierOptions *options = [[MPPImageClassifierOptions alloc] init]; options.baseOptions.modelAssetPath = modelPath; options.runningMode = MPPRunningModeImage; options.maxResults = 5; MPPImageClassifier *imageClassifier = [[MPPImageClassifier alloc] initWithOptions:options error:nil];
動画
@import MediaPipeTasksVision; NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"tflite"]; MPPImageClassifierOptions *options = [[MPPImageClassifierOptions alloc] init]; options.baseOptions.modelAssetPath = modelPath; options.runningMode = MPPRunningModeVideo; options.maxResults = 5; MPPImageClassifier *imageClassifier = [[MPPImageClassifier alloc] initWithOptions:options error:nil];
ライブ配信
@import MediaPipeTasksVision; // Class that conforms to the `MPPImageClassifierLiveStreamDelegate` protocol // and implements the method that the image classifier calls once it finishes // performing classification on each input frame. @interface APPImageClassifierResultProcessor : NSObject@end @implementation APPImageClassifierResultProcessor - (void)imageClassifier:(MPPImageClassifier *)imageClassifier didFinishClassificationWithResult:(MPPImageClassifierResult *)imageClassifierResult timestampInMilliseconds:(NSInteger)timestampInMilliseconds error:(NSError *)error { // Process the image classifier result or errors here. } @end NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model" ofType:@"tflite"]; MPPImageClassifierOptions *options = [[MPPImageClassifierOptions alloc] init]; options.baseOptions.modelAssetPath = modelPath; options.runningMode = MPPRunningModeLiveStream; options.maxResults = 5; // Assign an object of the class to the `imageClassifierLiveStreamDelegate` // property. APPImageClassifierResultProcessor *processor = [APPImageClassifierResultProcessor new]; options.imageClassifierLiveStreamDelegate = processor; MPPImageClassifier *imageClassifier = [[MPPImageClassifier alloc] initWithOptions:options error:nil];
構成オプション
このタスクには、iOS アプリの場合、次の構成オプションがあります。
オプション名 | 説明 | 値の範囲 | デフォルト値 |
---|---|---|---|
runningMode |
タスクの実行モードを設定します。3 つの
モード: IMAGE: 単一画像入力のモード。 VIDEO: 動画のデコードされたフレームのモード。 LIVE_STREAM: 入力のライブ配信のモード カメラからのデータなどです。このモードでは、resultListener は 結果を受け取るリスナーを設定するために呼び出されます。 使用できます。 |
{RunningMode.image, RunningMode.video, RunningMode.liveStream } |
RunningMode.image |
displayNamesLocale |
指定された表示名に使うラベルの言語を設定します。
タスクのモデルのメタデータ(利用可能な場合)。デフォルトは en です。
英語。カスタムモデルのメタデータにローカライズされたラベルを追加できます。
TensorFlow Lite Metadata Writer API を使用 |
言語 / 地域コード | en |
maxResults |
オプションの上位スコアの分類結果の最大数を設定します。 戻ります。<0 の場合、利用可能な結果がすべて返されます。 | 正の数 | -1 |
scoreThreshold |
予測スコアのしきい値を設定します。このしきい値は、 モデル メタデータ(存在する場合)この値を下回る結果は拒否されます。 | 任意の浮動小数点数 | 未設定 |
categoryAllowlist |
許可するカテゴリ名のオプション リストを設定します。空でない場合、
カテゴリ名がこのセットにない分類結果は、
フィルタで除外されます重複または不明なカテゴリ名は無視されます。
このオプションは categoryDenylist とは相互に排他的であり、
どちらの結果もエラーになります |
任意の文字列 | 未設定 |
categoryDenylist |
許可されていないカテゴリ名のオプション リストを設定します。条件
空でない場合、カテゴリ名がこのセットに含まれている分類結果はフィルタされます
できます。重複または不明なカテゴリ名は無視されます。このオプションは
categoryAllowlist と排他的であり、両方を使用するとエラーになります。 |
任意の文字列 | 未設定 |
resultListener |
分類結果を受け取るように結果リスナーを設定します。
非同期で行われます。
モードです。実行モードが LIVE_STREAM に設定されている場合にのみ使用できます |
なし | 未設定 |
ライブ配信の設定
実行モードがライブ ストリームに設定されている場合、画像分類器は
追加の imageClassifierLiveStreamDelegate
構成オプションがあり、
分類器が分類結果を非同期で配信できるようにします「
delegate は、
imageClassifier(_:didFinishClassification:timestampInMilliseconds:error:)
メソッドで、分類の処理後に画像分類器が呼び出します。
表示されます。
オプション名 | 説明 | 値の範囲 | デフォルト値 |
---|---|---|---|
imageClassifierLiveStreamDelegate |
画像分類器が分類結果を非同期で受信できるようにします
[ライブストリームモード]をクリックしますインスタンスがこのプロパティに設定されているクラスは、
実装する
imageClassifier(_:didFinishClassification:timestampInMilliseconds:error:)
メソッドを呼び出します。 |
該当なし | 未設定 |
データの準備
事前に入力画像またはフレームを MPImage
オブジェクトに変換する必要があります。
渡します。MPImage
はさまざまな種類の iOS 画像をサポートしています
形式があり、任意の実行モードで推論に使用できます。詳細
MPImage
の詳細については、
MPImage API
ユースケースと実行モードに基づいて、iOS 画像形式を選択してください
MPImage
は、UIImage
、CVPixelBuffer
、および
CMSampleBuffer
件の iOS 画像形式。
UIImage
UIImage
形式は、次の実行モードに適しています。
画像: App Bundle、ユーザー ギャラリー、ファイル システムの
UIImage
の画像はMPImage
オブジェクトに変換できます。動画: AVAssetImageGenerator を使用 動画フレームを抽出して CGImage
UIImage
の画像に変換します。
Swift
// Load an image on the user's device as an iOS `UIImage` object. // Convert the `UIImage` object to a MediaPipe's Image object having the default // orientation `UIImage.Orientation.up`. let image = try MPImage(uiImage: image)
Objective-C
// Load an image on the user's device as an iOS `UIImage` object. // Convert the `UIImage` object to a MediaPipe's Image object having the default // orientation `UIImageOrientationUp`. MPImage *image = [[MPPImage alloc] initWithUIImage:image error:nil];
この例では、MPImage
をデフォルトの
UIImage.Orientation.Up
方向です。MPImage
は、サポートされているいずれかの方法で初期化できます。
UIImage.Orientation
使用できます。画像分類器は、.upMirrored
のような画面の向きに対応していません。
.downMirrored
、.leftMirrored
、.rightMirrored
。
UIImage
の詳細については、UIImage Apple Developer をご覧ください。
ドキュメントをご覧ください。
CVPixelBuffer
CVPixelBuffer
形式はフレームを生成するアプリに適している
iOS の CoreImage を使用してください。
処理するためのフレームワークです。
CVPixelBuffer
形式は、次の実行モードに適しています。
画像: なんらかの処理後に
CVPixelBuffer
の画像を生成するアプリCoreImage
フレームワークを使用して送信されたモデルは、 構成されます動画: 動画フレームは
CVPixelBuffer
形式に変換できます。 動画モードで画像分類器に送信されますライブ ストリーム: iOS カメラを使用してフレームを生成するアプリは、 送信する前に、
CVPixelBuffer
形式に変換する ライブ配信モードの画像分類。
Swift
// Obtain a CVPixelBuffer. // Convert the `CVPixelBuffer` object to a MediaPipe's Image object having the default // orientation `UIImage.Orientation.up`. let image = try MPImage(pixelBuffer: pixelBuffer)
Objective-C
// Obtain a CVPixelBuffer. // Convert the `CVPixelBuffer` object to a MediaPipe's Image object having the // default orientation `UIImageOrientationUp`. MPImage *image = [[MPPImage alloc] initWithUIImage:image error:nil];
CVPixelBuffer
の詳細については、CVPixelBuffer Apple をご覧ください。
デベロッパー
ドキュメントをご覧ください。
CMSampleBuffer
CMSampleBuffer
形式では、統一されたメディアタイプのメディア サンプルが保存されます。
ライブ配信の実行モードに適していますiOS カメラのライブフレームは、
iOS によって CMSampleBuffer
形式で非同期に配信されます。
AVCaptureVideoDataOutput.
Swift
// Obtain a CMSampleBuffer. // Convert the `CMSampleBuffer` object to a MediaPipe's Image object having the default // orientation `UIImage.Orientation.up`. let image = try MPImage(sampleBuffer: sampleBuffer)
Objective-C
// Obtain a `CMSampleBuffer`. // Convert the `CMSampleBuffer` object to a MediaPipe's Image object having the // default orientation `UIImageOrientationUp`. MPImage *image = [[MPPImage alloc] initWithSampleBuffer:sampleBuffer error:nil];
CMSampleBuffer
の詳細については、CMSampleBuffer Apple をご覧ください。
デベロッパー
ドキュメントをご覧ください。
タスクを実行する
画像分類器を実行するには、割り当てられたオブジェクトに固有の classify()
メソッドを使用します。
実行モード:
- 静止画像:
classify(image:)
- 動画:
classify(videoFrame:timestampInMilliseconds:)
- ライブ配信:
classifyAsync(image:timestampInMilliseconds:)
Image Classifier は、 入力画像やフレームです。
次のコードサンプルは、Google Cloud で画像分類を実行する基本的な例を示しています。 実行モードが 3 つあります
Swift
画像
let result = try imageClassifier.classify(image: image)
動画
let result = try imageClassifier.classify( videoFrame: image, timestampInMilliseconds: timestamp)
ライブ配信
try imageClassifier.classifyAsync( image: image, timestampInMilliseconds: timestamp)
Objective-C
画像
MPPImageClassifierResult *result = [imageClassifier classifyImage:image error:nil];
動画
MPPImageClassifierResult *result = [imageClassifier classifyVideoFrame:image timestampInMilliseconds:timestamp error:nil];
ライブ配信
BOOL success = [imageClassifier classifyAsyncImage:image timestampInMilliseconds:timestamp error:nil];
画像分類器のコード例は、これらの各モードの実装を示しています。
詳細 classify(image:)
、
classify(videoFrame:timestampInMilliseconds:)
classifyAsync(image:timestampInMilliseconds:)
。サンプルコードでは
ユーザーが不要な処理モードを切り替えられるようにする
あります。
次の点にご留意ください。
動画モードまたはライブ配信モードで実行する場合は、 画像分類タスクへの入力フレームのタイムスタンプ。
画像モードまたは動画モードで実行している場合、画像分類タスクは 入力画像やフレームの処理が完了するまで待機しません。宛先 現在のスレッドをブロックせずにバックグラウンドで処理を実行 使用すると、 Dispatch または NSOperation 説明します。
ライブストリーム モードで実行すると、画像分類タスクがすぐに返されます。 現在のスレッドをブロックしません。このメソッドは、
imageClassifier(_:didFinishClassification:timestampInMilliseconds:error:)
各入力フレームを処理した後、分類結果とともに渡されます。「 画像分類器は、専用シリアル クエリで非同期にこのメソッドを呼び出します。 ディスパッチキューに格納されます。ユーザー インターフェースに結果を表示するには、 メインキューに送られます。もし 画像分類タスクがビジー状態になると、classifyAsync
関数が呼び出される 画像分類器は新しい入力フレームを無視します。
結果の処理と表示
推論を実行すると、画像分類タスクは
有効なカテゴリのリストを含む ImageClassifierResult
オブジェクト
オブジェクトを表現します
このタスクからの出力データの例を次に示します。
ImageClassifierResult:
Classifications #0 (single classification head):
head index: 0
category #0:
category name: "/m/01bwb9"
display name: "Passer domesticus"
score: 0.91406
index: 671
category #1:
category name: "/m/01bwbt"
display name: "Passer montanus"
score: 0.00391
index: 670
この結果は、Bird Classifier を実行して取得されました。 日付:
画像分類器のサンプルコードは、画像分類機能を表示する方法を示しています。 タスクから返された結果については、コード 例 をご覧ください。