AutoML Vision Edge を使用して独自のモデルをトレーニングしたら、そのモデルをアプリで使用して画像にラベルを付けることができます。
AutoML Vision Edge からトレーニングされたモデルを統合するには、モデルのファイルを Xcode プロジェクトにコピーしてバンドルする方法と、Firebase から動的にダウンロードする方法があります。
| モデルのバンドル オプション | |
|---|---|
| アプリにバンドル済み | 
      
  | 
  
| Firebase でホストする | 
      
  | 
  
始める前に
Podfile に ML Kit ライブラリを含めます。
モデルをアプリにバンドルする場合:
pod 'GoogleMLKit/ImageLabelingCustom'Firebase からモデルを動的にダウンロードするには、
LinkFirebase依存関係を追加します。pod 'GoogleMLKit/ImageLabelingCustom' pod 'GoogleMLKit/LinkFirebase'プロジェクトの Pod をインストールまたは更新した後に、
.xcworkspaceを使用して Xcode プロジェクトを開きます。ML Kit は Xcode バージョン 12.2 以降でサポートされています。モデルをダウンロードする場合は、Firebase を Android プロジェクトに追加します(まだ行っていない場合)。これは、モデルをバンドルする場合には必要ありません。
1. モデルを読み込む
ローカル モデルソースを構成する
モデルをアプリにバンドルするには:
Firebase コンソールからダウンロードした ZIP アーカイブから、モデルとそのメタデータをフォルダに抽出します。
your_model_directory |____dict.txt |____manifest.json |____model.tflite3 つのファイルすべてを同じフォルダに配置する必要があります。ダウンロードしたファイルは修正せずにそのまま使用することをおすすめします(ファイル名を含めて)。
フォルダを Xcode プロジェクトにコピーします。その際、[Create folder references] を選択するように注意してください。モデルファイルとメタデータはアプリバンドルに含まれ、ML Kit で利用できます。
モデル マニフェスト ファイルへのパスを指定して
LocalModelオブジェクトを作成します。Swift
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 オブジェクトを作成します。その際に、モデルを公開したときに割り当てた名前を指定します。
Swift
// 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 から非同期でモデルをダウンロードします。
Swift
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 オブジェクトからラベラーを作成し、必要な信頼スコアのしきい値を構成するだけで済みます(モデルを評価するを参照)。
Swift
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 をインスタンス化する、つまりラベラーを作成する(リモートモデルをダウンロード済みの場合はリモートモデルから、ダウンロードされていない場合はローカルモデルから作成する)ときに確認すると良いかもしれません。
Swift
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 の一部をグレー表示または非表示にするなど)を無効にする必要があります。
オブザーバをデフォルトの通知センターに接続して、モデルのダウンロード ステータスを取得できます。ダウンロードに時間がかかり、ダウンロードが終了するまでに元のオブジェクトが解放される可能性があります。このため、observer ブロックでは self への弱い参照を使用してください。次に例を示します。
Swift
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を指定してください。Swift
let image = VisionImage(image: uiImage) visionImage.orientation = image.imageOrientation
Objective-C
MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image]; visionImage.orientation = image.imageOrientation;
CMSampleBufferRef を使用する場合の手順は次のとおりです。
- 
    
CMSampleBufferRefバッファに含まれる画像データの向きを指定します。画像の向きは次のように取得します。
Swift
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オブジェクトを作成します。Swift
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. 画像ラベラーを実行する
非同期:
Swift
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.
     }];
同期:
Swift
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 モデルファイルのメタデータで使用できる場合)、信頼スコア、インデックスを取得できます。次に例を示します。
Swift
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 回で済みます。例については、ショーケース サンプルアプリの previewOverlayView クラスと FIRDetectionOverlayView クラスをご覧ください。