AutoML VisionEdgeからトレーニングされたモデルを統合する方法は2つあります。モデルのファイルをXcodeプロジェクトにコピーしてモデルをバンドルすることも、Firebaseから動的にダウンロードすることもできます。
モデルバンドルオプション | |
---|---|
アプリにバンドルされています |
|
Firebaseでホスト |
|
あなたが始める前に
ポッドファイルにMLキットライブラリを含めます。
モデルをアプリにバンドルする場合:
pod 'GoogleMLKit/ImageLabelingCustom'
Firebaseからモデルを動的にダウンロードするには、
LinkFirebase
の依存関係を追加します。pod 'GoogleMLKit/ImageLabelingCustom' pod 'GoogleMLKit/LinkFirebase'
プロジェクトのポッドをインストールまたは更新した後、
.xcworkspace
を使用してXcodeプロジェクトを開きます。 ML Kitは、Xcodeバージョン12.2以降でサポートされています。モデルをダウンロードする場合は、AndroidプロジェクトにFirebaseを追加してください(まだ追加していない場合)。モデルをバンドルする場合、これは必要ありません。
1.モデルをロードします
ローカルモデルソースを構成する
モデルをアプリにバンドルするには:
Firebaseコンソールからダウンロードしたzipアーカイブからモデルとそのメタデータをフォルダーに抽出します。
your_model_directory |____dict.txt |____manifest.json |____model.tflite
3つのファイルはすべて同じフォルダーにある必要があります。ダウンロードしたファイルは、変更せずに(ファイル名を含めて)使用することをお勧めします。
フォルダをXcodeプロジェクトにコピーします。その際、[フォルダ参照の作成]を選択するように注意してください。モデルファイルとメタデータはアプリバンドルに含まれ、MLキットで利用できるようになります。
モデルマニフェストファイルへのパスを指定して、
LocalModel
オブジェクトを作成します。迅速
guard let manifestPath = Bundle.main.path( forResource: "manifest", ofType: "json", inDirectory: "your_model_directory" ) else { return true } let localModel = LocalModel(manifestPath: manifestPath)
Objective-C
NSString *manifestPath = [NSBundle.mainBundle pathForResource:@"manifest" ofType:@"json" inDirectory:@"your_model_directory"]; MLKLocalModel *localModel = [[MLKLocalModel alloc] initWithManifestPath:manifestPath];
Firebaseでホストされているモデルソースを設定する
リモートでホストされるモデルを使用するには、モデルを公開したときにモデルに割り当てた名前を指定して、 CustomRemoteModel
オブジェクトを作成します。
迅速
// Initialize the model source with the name you assigned in
// the Firebase console.
let remoteModelSource = FirebaseModelSource(name: "your_remote_model")
let remoteModel = CustomRemoteModel(remoteModelSource: remoteModelSource)
Objective-C
// Initialize the model source with the name you assigned in
// the Firebase console.
MLKFirebaseModelSource *firebaseModelSource =
[[MLKFirebaseModelSource alloc] initWithName:@"your_remote_model"];
MLKCustomRemoteModel *remoteModel =
[[MLKCustomRemoteModel alloc] initWithRemoteModelSource:firebaseModelSource];
次に、ダウンロードを許可する条件を指定して、モデルのダウンロードタスクを開始します。モデルがデバイスにない場合、またはモデルの新しいバージョンが利用可能な場合、タスクはFirebaseからモデルを非同期でダウンロードします。
迅速
let downloadConditions = ModelDownloadConditions(
allowsCellularAccess: true,
allowsBackgroundDownloading: true
)
let downloadProgress = ModelManager.modelManager().download(
remoteModel,
conditions: downloadConditions
)
Objective-C
MLKModelDownloadConditions *downloadConditions =
[[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:YES
allowsBackgroundDownloading:YES];
NSProgress *downloadProgress =
[[MLKModelManager modelManager] downloadRemoteModel:remoteModel
conditions:downloadConditions];
多くのアプリは初期化コードでダウンロードタスクを開始しますが、モデルを使用する前であればいつでもダウンロードできます。
モデルから画像ラベラーを作成します
モデルソースを設定したら、そのうちの1つからImageLabeler
オブジェクトを作成します。
ローカルにバンドルされたモデルしかない場合は、 LocalModel
オブジェクトからラベラーを作成し、必要な信頼スコアのしきい値を構成するだけです(モデルの評価を参照)。
迅速
let options = CustomImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = NSNumber(value: 0.0) // Evaluate your model in the Cloud console
// to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options)
Objective-C
CustomImageLabelerOptions *options =
[[CustomImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = @(0.0f); // Evaluate your model in the Cloud console
// to determine an appropriate value.
MLKImageLabeler *imageLabeler =
[MLKImageLabeler imageLabelerWithOptions:options];
リモートでホストされているモデルを使用している場合は、実行する前に、モデルがダウンロードされていることを確認する必要があります。モデルマネージャーのisModelDownloaded(remoteModel:)
メソッドを使用して、モデルダウンロードタスクのステータスを確認できます。
ラベラーを実行する前にこれを確認するだけで済みますが、リモートでホストされているモデルとローカルにバンドルされているモデルの両方がある場合は、 ImageLabeler
をインスタンス化するときにこのチェックを実行するのが理にかなっています。ダウンロードされ、それ以外の場合はローカルモデルからダウンロードされます。
迅速
var options: CustomImageLabelerOptions
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
options = CustomImageLabelerOptions(remoteModel: remoteModel)
} else {
options = CustomImageLabelerOptions(localModel: localModel)
}
options.confidenceThreshold = NSNumber(value: 0.0) // Evaluate your model in the Firebase console
// to determine an appropriate value.
let imageLabeler = ImageLabeler.imageLabeler(options: options)
Objective-C
MLKCustomImageLabelerOptions *options;
if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) {
options = [[MLKCustomImageLabelerOptions alloc] initWithRemoteModel:remoteModel];
} else {
options = [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
}
options.confidenceThreshold = @(0.0f); // Evaluate your model in the Firebase console
// to determine an appropriate value.
MLKImageLabeler *imageLabeler =
[MLKImageLabeler imageLabelerWithOptions:options];
リモートでホストされているモデルしかない場合は、モデルがダウンロードされたことを確認するまで、モデル関連の機能(UIの一部をグレーアウトまたは非表示にするなど)を無効にする必要があります。
オブザーバーをデフォルトの通知センターに接続することで、モデルのダウンロードステータスを取得できます。ダウンロードには時間がかかる可能性があり、ダウンロードが完了するまでに元のオブジェクトが解放される可能性があるため、オブザーバーブロックでは必ずself
への弱参照を使用してください。例えば:
迅速
NotificationCenter.default.addObserver(
forName: .mlkitMLModelDownloadDidSucceed,
object: nil,
queue: nil
) { [weak self] notification in
guard let strongSelf = self,
let userInfo = notification.userInfo,
let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
as? RemoteModel,
model.name == "your_remote_model"
else { return }
// The model was downloaded and is available on the device
}
NotificationCenter.default.addObserver(
forName: .mlkitMLModelDownloadDidFail,
object: nil,
queue: nil
) { [weak self] notification in
guard let strongSelf = self,
let userInfo = notification.userInfo,
let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
as? RemoteModel
else { return }
let error = userInfo[ModelDownloadUserInfoKey.error.rawValue]
// ...
}
Objective-C
__weak typeof(self) weakSelf = self;
[NSNotificationCenter.defaultCenter
addObserverForName:MLKModelDownloadDidSucceedNotification
object:nil
queue:nil
usingBlock:^(NSNotification *_Nonnull note) {
if (weakSelf == nil | note.userInfo == nil) {
return;
}
__strong typeof(self) strongSelf = weakSelf;
MLKRemoteModel *model = note.userInfo[MLKModelDownloadUserInfoKeyRemoteModel];
if ([model.name isEqualToString:@"your_remote_model"]) {
// The model was downloaded and is available on the device
}
}];
[NSNotificationCenter.defaultCenter
addObserverForName:MLKModelDownloadDidFailNotification
object:nil
queue:nil
usingBlock:^(NSNotification *_Nonnull note) {
if (weakSelf == nil | note.userInfo == nil) {
return;
}
__strong typeof(self) strongSelf = weakSelf;
NSError *error = note.userInfo[MLKModelDownloadUserInfoKeyError];
}];
2.入力画像を準備します
UIImage
またはCMSampleBufferRef
を使用してVisionImage
オブジェクトを作成します。
UIImage
を使用する場合は、次の手順に従います。
-
UIImage
を使用してVisionImage
オブジェクトを作成します。必ず正しい.orientation
を指定してください。迅速
let image = VisionImage(image: uiImage) visionImage.orientation = image.imageOrientation
Objective-C
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image]; visionImage.orientation = image.imageOrientation;
CMSampleBufferRef
を使用する場合は、次の手順に従ってください。
CMSampleBufferRef
バッファーに含まれる画像データの方向を指定します。画像の向きを取得するには:
迅速
func imageOrientation( deviceOrientation: UIDeviceOrientation, cameraPosition: AVCaptureDevice.Position ) -> UIImage.Orientation { switch deviceOrientation { case .portrait: return cameraPosition == .front ? .leftMirrored : .right case .landscapeLeft: return cameraPosition == .front ? .downMirrored : .up case .portraitUpsideDown: return cameraPosition == .front ? .rightMirrored : .left case .landscapeRight: return cameraPosition == .front ? .upMirrored : .down case .faceDown, .faceUp, .unknown: return .up } }
Objective-C
- (UIImageOrientation) imageOrientationFromDeviceOrientation:(UIDeviceOrientation)deviceOrientation cameraPosition:(AVCaptureDevicePosition)cameraPosition { switch (deviceOrientation) { case UIDeviceOrientationPortrait: return position == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored : UIImageOrientationRight; case UIDeviceOrientationLandscapeLeft: return position == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored : UIImageOrientationUp; case UIDeviceOrientationPortraitUpsideDown: return position == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored : UIImageOrientationLeft; case UIDeviceOrientationLandscapeRight: return position == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored : UIImageOrientationDown; case UIDeviceOrientationUnknown: case UIDeviceOrientationFaceUp: case UIDeviceOrientationFaceDown: return UIImageOrientationUp; } }
-
CMSampleBufferRef
オブジェクトと方向を使用してVisionImage
オブジェクトを作成します。迅速
let image = VisionImage(buffer: sampleBuffer) image.orientation = imageOrientation( deviceOrientation: UIDevice.current.orientation, cameraPosition: cameraPosition)
Objective-C
MLKVisionImage *image = [[MLKVisionImage alloc] initWithBuffer:sampleBuffer]; image.orientation = [self imageOrientationFromDeviceOrientation:UIDevice.currentDevice.orientation cameraPosition:cameraPosition];
3.イメージラベラーを実行します
非同期:
迅速
imageLabeler.process(image) { labels, error in
guard error == nil, let labels = labels, !labels.isEmpty else {
// Handle the error.
return
}
// Show results.
}
Objective-C
[imageLabeler
processImage:image
completion:^(NSArray<MLKImageLabel *> *_Nullable labels,
NSError *_Nullable error) {
if (label.count == 0) {
// Handle the error.
return;
}
// Show results.
}];
同期的に:
迅速
var labels: [ImageLabel]
do {
labels = try imageLabeler.results(in: image)
} catch let error {
// Handle the error.
return
}
// Show results.
Objective-C
NSError *error;
NSArray<MLKImageLabel *> *labels =
[imageLabeler resultsInImage:image error:&error];
// Show results or handle the error.
4.ラベル付けされたオブジェクトに関する情報を取得します
画像のラベル付け操作が成功すると、ImageLabel
の配列が返されます。各ImageLabel
は、画像でラベル付けされたものを表します。各ラベルのテキストの説明(TensorFlow Liteモデルファイルのメタデータで利用可能な場合)、信頼スコア、およびインデックスを取得できます。例えば: 迅速
for label in labels {
let labelText = label.text
let confidence = label.confidence
let index = label.index
}
Objective-C
for (MLKImageLabel *label in labels) {
NSString *labelText = label.text;
float confidence = label.confidence;
NSInteger index = label.index;
}
リアルタイムパフォーマンスを改善するためのヒント
リアルタイムアプリケーションで画像にラベルを付ける場合は、次のガイドラインに従って、最高のフレームレートを実現してください。
- スロットルが検出器を呼び出します。検出器の実行中に新しいビデオフレームが使用可能になった場合は、フレームをドロップします。
- 検出器の出力を使用して入力画像にグラフィックをオーバーレイする場合は、最初に結果を取得してから、画像とオーバーレイを1つのステップでレンダリングします。そうすることで、入力フレームごとに1回だけ表示面にレンダリングします。例については、showcaseサンプルアプリのpreviewOverlayViewクラスとFIRDetectionOverlayViewクラスを参照してください。