iOS에서 커스텀 모델을 사용하여 이미지 라벨 지정

ML Kit를 사용하면 이미지에서 항목을 인식하고 라벨을 지정할 수 있습니다. 이 API는 다양한 커스텀 이미지 분류 모델을 지원합니다. 모델 호환성 요구사항, 사전 학습된 모델을 찾을 수 있는 위치, 자체 모델을 학습하는 방법은 ML Kit의 커스텀 모델을 참고하세요.

커스텀 모델을 통합하는 방법에는 두 가지가 있습니다. 모델을 앱의 애셋 폴더 안에 넣어 번들로 묶거나 Cloud Storage에서 동적으로 다운로드할 수 있습니다. 다음 표에서는 두 가지 옵션을 비교합니다.

번들 모델 호스팅된 모델
모델이 앱 APK에 포함되어 크기가 커집니다. 모델이 APK에 포함되지 않습니다. Cloud Storage에 업로드하여 호스팅됩니다. Firebase용 Cloud Storage를 사용하는 것이 좋습니다.
Android 기기가 오프라인 상태일 때도 모델을 즉시 사용할 수 있습니다. 앱에 모델을 주문형으로 다운로드하는 코드가 포함되어야 합니다.
Firebase 프로젝트가 필요 없음 Firebase 프로젝트가 필요합니다 (Firebase용 Cloud Storage를 사용하는 경우).
모델을 업데이트하려면 앱을 다시 게시해야 합니다. 앱을 다시 게시하지 않고 모델 업데이트 푸시
기본 제공 A/B 테스트 없음 Firebase 원격 구성으로 A/B 테스트

사용해 보기

시작하기 전에

  1. Podfile에 ML Kit 라이브러리를 포함합니다.

    pod 'GoogleMLKit/ImageLabelingCustom', '8.0.0'
    
  2. 프로젝트의 포드를 설치하거나 업데이트한 후 .xcworkspace를 사용하여 Xcode 프로젝트를 엽니다. ML Kit는 Xcode 13.2.1 이상 버전에서 지원됩니다.

  3. Firebase용 Cloud Storage를 사용하여 모델을 다운로드하려면 iOS 프로젝트에 Firebase를 추가(아직 추가하지 않은 경우)해야 합니다. 모델을 번들로 묶을 때는 이 작업이 필요하지 않습니다.

1. 모델 로드

로컬 모델 소스 구성

모델을 앱과 함께 번들로 묶는 방법은 다음과 같습니다.

  1. 모델 파일(일반적으로 .tflite 또는 .lite로 끝남)을 Xcode 프로젝트에 복사합니다. 이때 Copy bundle resources(번들 리소스 복사)를 선택해야 합니다. 모델 파일이 App Bundle에 포함되며 ML Kit에서 사용할 수 있습니다.

  2. LocalModel 객체를 만듭니다. 모델 파일의 경로를 지정합니다.

    Swift

    let localModel = LocalModel(path: localModelFilePath)

    Objective-C

    MLKLocalModel *localModel =
        [[MLKLocalModel alloc] initWithPath:localModelFilePath];

원격 호스팅 모델 소스 구성

원격 호스팅 모델을 사용하려면 자체 앱 로직을 사용하여 모델 파일을 기기의 로컬 저장소에 다운로드한 후 로컬 모델로 로드해야 합니다. Firebase용 Cloud Storage를 사용하여 모델을 호스팅하는 것이 좋습니다. 구현에 관한 자세한 내용은 Firebase ML에서 Cloud Storage로의 마이그레이션 가이드를 참고하세요.

이미지 라벨러 구성

모델 소스를 구성한 후 모델 소스 중 하나에서 ImageLabeler 객체를 만듭니다.

사용할 수 있는 옵션은 다음과 같습니다.

옵션
confidenceThreshold

감지된 라벨의 최소 신뢰도 점수입니다. 설정하지 않으면 모델의 메타데이터에 지정된 분류기 임계값이 사용됩니다. 모델에 메타데이터가 없거나 메타데이터에 분류기 임계값이 지정되어 있지 않으면 기본 임계값인 0.0이 사용됩니다.

maxResultCount

반환할 라벨의 최대 개수입니다. 설정하지 않으면 기본값인 10이 사용됩니다.

로컬로 번들된 모델만 있다면 LocalModel 객체에서 라벨러를 만듭니다.

Swift

let options = CustomImageLabelerOptions(localModel: localModel)
options.confidenceThreshold = NSNumber(value: 0.0)
let imageLabeler = ImageLabeler.imageLabeler(options: options)

Objective-C

MLKCustomImageLabelerOptions *options =
    [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
options.confidenceThreshold = @(0.0);
MLKImageLabeler *imageLabeler =
    [MLKImageLabeler imageLabelerWithOptions:options];

원격 호스팅 모델이 있다면 실행 전에 모델이 다운로드되었는지 확인해야 합니다.

이 상태는 라벨러 실행 전에만 확인하면 되지만 원격 호스팅 모델과 로컬로 번들된 모델이 모두 있는 경우에는 ImageLabeler를 인스턴스화할 때 이 확인 작업을 수행하는 것이 합리적일 수 있습니다. 원격 모델이 다운로드되었으면 원격 모델에서, 그렇지 않으면 로컬 모델에서 라벨러를 만듭니다.

Swift

// Path where your download logic saves the model
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let localModelURL = documentDirectory.appendingPathComponent("my_remote_model.tflite")

let model: LocalModel
if FileManager.default.fileExists(atPath: localModelURL.path) {
  // Use the downloaded model
  model = LocalModel(path: localModelURL.path)
} else {
  // Fall back to bundled model
  guard let bundledModelPath = Bundle.main.path(forResource: "model", ofType: "tflite") else { return }
  model = LocalModel(path: bundledModelPath)
}

let options = CustomImageLabelerOptions(localModel: model)
let imageLabeler = ImageLabeler.imageLabeler(options: options)

Objective-C

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *localModelPath = [documentsDirectory stringByAppendingPathComponent:@"my_remote_model.tflite"];

MLKLocalModel *model;
if ([NSFileManager.defaultManager fileExistsAtPath:localModelPath]) {
  // Use the downloaded model
  model = [[MLKLocalModel alloc] initWithPath:localModelPath];
} else {
  // Fall back to bundled model
  NSString *bundledModelPath = [NSBundle.mainBundle pathForResource:@"model" ofType:@"tflite"];
  model = [[MLKLocalModel alloc] initWithPath:bundledModelPath];
}

MLKCustomImageLabelerOptions *options = [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:model];
MLKImageLabeler *imageLabeler = [MLKImageLabeler imageLabelerWithOptions:options];

원격 호스팅 모델만 있다면 모델 다운로드 여부가 확인될 때까지 모델 관련 기능 사용을 중지해야 합니다(예: UI 비활성화 또는 숨김).

Swift

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let localModelURL = documentDirectory.appendingPathComponent("my_remote_model.tflite")
if FileManager.default.fileExists(atPath: localModelURL.path) {
  // Model is already cached, initialize immediately
  self.initializeLabeler(with: localModelURL)
} else {
  // Model is not yet available, show loading UI and start download
  self.showLoadingUI()
  let storage = Storage.storage()
  let modelRef = storage.reference(forURL: "gs://YOUR_BUCKET/path/to/model.tflite")
  modelRef.write(toFile: localModelURL) { url, error in
    self.hideLoadingUI()
    if let error = error {
      // Handle download error
      self.showErrorUI()
    } else if let modelURL = url {
      // Download success, initialize labeler
      self.initializeLabeler(with: modelURL)
    }
  }
}

func initializeLabeler(with modelURL: URL) {
  let localModel = LocalModel(path: modelURL.path)
  let options = CustomImageLabelerOptions(localModel: localModel)
  self.imageLabeler = ImageLabeler.imageLabeler(options: options)
  // Enable ML-related UI features here
  self.enableMLFeatures()
}

Objective-C

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *localModelPath = [documentsDirectory stringByAppendingPathComponent:@"my_remote_model.tflite"];
NSURL *localModelURL = [NSURL fileURLWithPath:localModelPath];

if ([NSFileManager.defaultManager fileExistsAtPath:localModelPath]) {
  // Model is already cached, initialize immediately
  [self initializeLabelerWithURL:localModelURL];
} else {
  // Model is not yet available, show loading UI and start download
  [self showLoadingUI];

  FIRStorage *storage = [FIRStorage storage];
  FIRStorageReference *modelRef = [storage referenceForURL:@"gs://YOUR_BUCKET/path/to/model.tflite"];

  [modelRef writeToFile:localModelURL
             completion:^(NSURL * _Nullable URL, NSError * _Nullable error) {
               [self hideLoadingUI];
               if (error != nil) {
                 // Handle download error
                 [self showErrorUI];
               } else {
                 // Download success, initialize labeler
                 [self initializeLabelerWithURL:URL];
               }
             }];
}

- (void)initializeLabelerWithURL:(NSURL *)modelURL {
  MLKLocalModel *localModel = [[MLKLocalModel alloc] initWithPath:modelURL.path];
  MLKCustomImageLabelerOptions *options = [[MLKCustomImageLabelerOptions alloc] initWithLocalModel:localModel];
  self.imageLabeler = [MLKImageLabeler imageLabelerWithOptions:options];

  // Enable ML-related UI features here
  [self enableMLFeatures];
}

2. 입력 이미지 준비

UIImage 또는 CMSampleBuffer를 사용하여 VisionImage 객체를 만듭니다.

UIImage를 사용하는 경우 다음 단계를 따르세요.

  • UIImageVisionImage 객체를 만듭니다. 올바른 .orientation을 지정해야 합니다.

    Swift

    let image = VisionImage(image: UIImage)
    visionImage.orientation = image.imageOrientation

    Objective-C

    MLKVisionImage *visionImage = [[MLKVisionImage alloc] initWithImage:image];
    visionImage.orientation = image.imageOrientation;

CMSampleBuffer를 사용하는 경우 다음 단계를 따르세요.

  • ` CMSampleBuffer`에 포함된 이미지 데이터의 방향을 지정합니다.

    이미지 방향을 가져오는 방법은 다음과 같습니다.

    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 cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationLeftMirrored
                                                                : UIImageOrientationRight;
    
        case UIDeviceOrientationLandscapeLeft:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationDownMirrored
                                                                : UIImageOrientationUp;
        case UIDeviceOrientationPortraitUpsideDown:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationRightMirrored
                                                                : UIImageOrientationLeft;
        case UIDeviceOrientationLandscapeRight:
          return cameraPosition == AVCaptureDevicePositionFront ? UIImageOrientationUpMirrored
                                                                : UIImageOrientationDown;
        case UIDeviceOrientationUnknown:
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
          return UIImageOrientationUp;
      }
    }
          
  • VisionImage 객체와 CMSampleBuffer 객체 및 방향을 사용하여 객체를 만듭니다.

    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. 이미지 라벨러 실행

이미지에서 객체에 라벨을 지정하려면 image 객체를 ImageLabelerprocess() 메서드에 전달합니다.

비동기식으로:

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 *_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 *labels =
    [imageLabeler resultsInImage:image error:&error];
// Show results or handle the error.

4. 라벨이 지정된 항목 정보 가져오기

이미지 라벨 지정 작업이 성공하면 ImageLabel 배열이 반환됩니다. 각 ImageLabel은 이미지에서 라벨이 지정된 항목을 나타냅니다. 각 라벨의 텍스트 설명 (LiteRT 모델 파일의 메타데이터에 표시되는 경우), 신뢰도 점수, 색인을 가져올 수 있습니다. 예를 들면 다음과 같습니다.

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;
}

실시간 성능 향상을 위한 팁

실시간 애플리케이션에서 이미지 라벨을 지정하려는 경우 최상의 프레임 속도를 얻으려면 다음 안내를 따르세요.

  • 동영상 프레임을 처리하려면 감지기의 results(in:) 동기식 API를 사용합니다. AVCaptureVideoDataOutputSampleBufferDelegate's captureOutput(_, didOutput:from:) 함수에서 이 메서드를 호출하여 지정된 동영상 프레임에서 결과를 동기식으로 가져옵니다. AVCaptureVideoDataOutput alwaysDiscardsLateVideoFramestrue로 유지하여 감지기 호출을 제한합니다. 감지기가 실행 중일 때 새 동영상 프레임이 제공되면 삭제됩니다.
  • 감지기 출력을 사용해서 입력 이미지에서 그래픽을 오버레이하는 경우 먼저 ML Kit에서 결과를 가져온 후 이미지를 렌더링하고 단일 단계로 오버레이합니다. 이렇게 하면 처리된 입력 프레임별로 한 번만 디스플레이 표면에 렌더링됩니다. 예시는 ML Kit 빠른 시작 샘플의 updatePreviewOverlayViewWithLastFrame 을 참고하세요.