iOS에서 커스텀 분류 모델을 사용하여 객체 감지, 추적, 분류

ML Kit를 사용하면 연속적인 동영상 프레임에서 객체를 감지하고 추적할 수 있습니다.

ML Kit에 이미지를 전달하면 이미지에서 각 객체의 위치와 함께 최대 5개의 객체를 감지합니다. 동영상 스트림에서 객체를 감지할 때 각 객체에는 프레임 간에 객체를 추적하는 데 사용할 수 있는 고유 ID가 있습니다.

커스텀 이미지 분류 모델을 사용하여 감지된 객체를 분류할 수 있습니다. 모델 호환성 요구사항, 선행 학습된 모델을 찾을 수 있는 위치, 자체 모델을 학습시키는 방법에 대한 안내는 ML Kit가 있는 커스텀 모델을 참조하세요.

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

번들된 모델 호스팅된 모델
이 모델은 앱의 .ipa 파일에 포함되어 있기 때문에 모델 크기가 늘어납니다. 모델이 앱의 .ipa 파일에 없습니다. Firebase 머신러닝에 업로드하여 호스팅됩니다.
Android 기기가 오프라인 상태일 때도 모델을 즉시 사용할 수 있음 모델이 요청 시 다운로드됨
Firebase 프로젝트가 필요 없음 Firebase 프로젝트 필요
모델을 업데이트하려면 앱을 다시 게시해야 합니다. 앱을 다시 게시하지 않고 모델 업데이트 푸시
기본 제공되는 A/B 테스트 없음 Firebase 원격 구성으로 간편하게 A/B 테스트

사용해 보기

시작하기 전에

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

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

    pod 'GoogleMLKit/ObjectDetectionCustom', '3.2.0'
    

    Firebase에서 모델을 동적으로 다운로드하려면 LinkFirebase 종속 항목을 추가합니다.

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

  3. 모델을 다운로드하려면 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 호스팅 모델 소스 구성

원격 호스팅 모델을 사용하려면 모델을 게시할 때 모델에 할당한 이름을 지정하여 CustomRemoteModel 객체를 만듭니다.

Swift

let firebaseModelSource = FirebaseModelSource(
    name: "your_remote_model") // The name you assigned in
                               // the Firebase console.
let remoteModel = CustomRemoteModel(remoteModelSource: firebaseModelSource)

Objective-C

MLKFirebaseModelSource *firebaseModelSource =
    [[MLKFirebaseModelSource alloc]
        initWithName:@"your_remote_model"]; // The name you assigned in
                                            // the Firebase console.
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] downloadModel:remoteModel
                                       conditions:downloadConditions];

대부분의 앱은 초기화 코드에서 다운로드 작업을 시작하지만 모델 사용이 필요한 시점 이전에 언제든지 다운로드할 수 있습니다.

2. 객체 인식기 구성

모델 소스를 구성한 후 CustomObjectDetectorOptions 객체를 사용하여 사용 사례에 대한 객체 감지기를 구성합니다. 다음 설정을 변경할 수 있습니다.

객체 감지기 설정
감지 모드 STREAM_MODE (기본값) | SINGLE_IMAGE_MODE

STREAM_MODE(기본값)에서는 객체 감지기가 짧은 지연 시간으로 실행되지만, 감지기를 처음 몇 번 호출할 때 경계 상자 또는 카테고리 라벨이 지정되지 않는 등 불완전한 결과가 나올 수 있습니다. 또한 STREAM_MODE에서는 감지기가 객체에 추적 ID를 할당하며, 이 ID를 사용하여 여러 프레임 간에 객체를 추적할 수 있습니다. 객체를 추적하려고 하거나 실시간 동영상 스트림 처리와 같이 짧은 지연 시간이 중요한 경우에 이 모드를 사용하세요.

SINGLE_IMAGE_MODE에서 객체 인식기는 객체의 경계 상자가 결정되면 결과를 반환합니다. 분류도 사용 설정하는 경우 경계 상자와 카테고리 라벨을 모두 사용할 수 있게 되면 결과가 반환됩니다. 따라서 감지 지연 시간이 길어질 수 있습니다. 또한 SINGLE_IMAGE_MODE에서는 추적 ID가 할당되지 않습니다. 지연 시간이 중요하지 않고 부분적인 결과를 처리하지 않으려는 경우 이 모드를 사용하세요.

여러 객체 인식 및 추적 false (기본값) | true

최대 5개의 객체를 감지하고 추적할지, 아니면 가장 눈에 띄는 객체만 감지하고 추적할지 여부입니다 (기본값).

객체 분류 false (기본값) | true

제공된 맞춤 분류 기준 모델을 사용하여 감지된 객체를 분류할지 여부입니다. 커스텀 분류 모델을 사용하려면 true로 설정해야 합니다.

분류 신뢰도 기준

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

객체당 최대 라벨 수

감지기가 반환할 객체당 최대 라벨 수입니다. 설정하지 않으면 기본값 10이 사용됩니다.

로컬로 번들된 모델만 있다면 LocalModel 객체에서 객체 감지기를 만듭니다.

Swift

let options = CustomObjectDetectorOptions(localModel: localModel)
options.detectorMode = .singleImage
options.shouldEnableClassification = true
options.shouldEnableMultipleObjects = true
options.classificationConfidenceThreshold = NSNumber(value: 0.5)
options.maxPerObjectLabelCount = 3

Objective-C

MLKCustomObjectDetectorOptions *options =
    [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel];
options.detectorMode = MLKObjectDetectorModeSingleImage;
options.shouldEnableClassification = YES;
options.shouldEnableMultipleObjects = YES;
options.classificationConfidenceThreshold = @(0.5);
options.maxPerObjectLabelCount = 3;

원격 호스팅 모델이 있다면 실행 전에 모델이 다운로드되었는지 확인해야 합니다. 모델 관리자의 isModelDownloaded(remoteModel:) 메서드로 모델 다운로드 작업의 상태를 확인할 수 있습니다.

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

Swift

var options: CustomObjectDetectorOptions!
if (ModelManager.modelManager().isModelDownloaded(remoteModel)) {
  options = CustomObjectDetectorOptions(remoteModel: remoteModel)
} else {
  options = CustomObjectDetectorOptions(localModel: localModel)
}
options.detectorMode = .singleImage
options.shouldEnableClassification = true
options.shouldEnableMultipleObjects = true
options.classificationConfidenceThreshold = NSNumber(value: 0.5)
options.maxPerObjectLabelCount = 3

Objective-C

MLKCustomObjectDetectorOptions *options;
if ([[MLKModelManager modelManager] isModelDownloaded:remoteModel]) {
  options = [[MLKCustomObjectDetectorOptions alloc] initWithRemoteModel:remoteModel];
} else {
  options = [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel];
}
options.detectorMode = MLKObjectDetectorModeSingleImage;
options.shouldEnableClassification = YES;
options.shouldEnableMultipleObjects = YES;
options.classificationConfidenceThreshold = @(0.5);
options.maxPerObjectLabelCount = 3;

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

기본 알림 센터에 관찰자를 연결하여 모델 다운로드 상태를 가져올 수 있습니다. 다운로드하는 데 시간이 걸릴 수 있고 다운로드가 완료되면 원래 객체가 해제될 수 있으므로 관찰자 블록의 self에 약한 참조를 사용하세요. 예를 들면 다음과 같습니다.

Swift

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidSucceed,
    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: .mlkitModelDownloadDidFail,
    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];
            }];

객체 감지 및 추적 API는 다음 2가지 핵심 사용 사례에 최적화되어 있습니다.

  • 카메라 뷰파인더에서 가장 뚜렷한 객체의 실시간 감지 및 추적
  • 정적 이미지에서 여러 객체 감지

이러한 사용 사례에 맞게 API를 구성하는 방법은 다음과 같습니다.

Swift

// Live detection and tracking
let options = CustomObjectDetectorOptions(localModel: localModel)
options.shouldEnableClassification = true
options.maxPerObjectLabelCount = 3

// Multiple object detection in static images
let options = CustomObjectDetectorOptions(localModel: localModel)
options.detectorMode = .singleImage
options.shouldEnableMultipleObjects = true
options.shouldEnableClassification = true
options.maxPerObjectLabelCount = 3

Objective-C

// Live detection and tracking
MLKCustomObjectDetectorOptions *options =
    [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel];
options.shouldEnableClassification = YES;
options.maxPerObjectLabelCount = 3;

// Multiple object detection in static images
MLKCustomObjectDetectorOptions *options =
    [[MLKCustomObjectDetectorOptions alloc] initWithLocalModel:localModel];
options.detectorMode = MLKObjectDetectorModeSingleImage;
options.shouldEnableMultipleObjects = YES;
options.shouldEnableClassification = YES;
options.maxPerObjectLabelCount = 3;

3. 입력 이미지 준비

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;
      }
    }
          
  • CMSampleBuffer 객체와 방향을 사용하여 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];

4. 객체 감지기 만들기 및 실행

  1. 새 객체 인식기를 만듭니다.

    Swift

    let objectDetector = ObjectDetector.objectDetector(options: options)

    Objective-C

    MLKObjectDetector *objectDetector = [MLKObjectDetector objectDetectorWithOptions:options];
  2. 그런 다음 검사 프로그램을 사용합니다.

    비동기식:

    Swift

    objectDetector.process(image) { objects, error in
        guard error == nil, let objects = objects, !objects.isEmpty else {
            // Handle the error.
            return
        }
        // Show results.
    }

    Objective-C

    [objectDetector
        processImage:image
          completion:^(NSArray *_Nullable objects,
                       NSError *_Nullable error) {
            if (objects.count == 0) {
                // Handle the error.
                return;
            }
            // Show results.
         }];

    동기식으로:

    Swift

    var objects: [Object]
    do {
        objects = try objectDetector.results(in: image)
    } catch let error {
        // Handle the error.
        return
    }
    // Show results.

    Objective-C

    NSError *error;
    NSArray *objects =
        [objectDetector resultsInImage:image error:&error];
    // Show results or handle the error.

5. 라벨이 지정된 객체 정보 가져오기

이미지 프로세서 호출이 성공하면 비동기 메서드를 호출했는지 동기 메서드를 호출했는지에 따라 완료 핸들러에 Object 목록을 전달하거나 목록을 반환합니다.

Object에는 다음 속성이 포함됩니다.

frame 이미지에서 객체의 위치를 나타내는 CGRect입니다.
trackingID 여러 이미지 간에 객체를 식별하는 정수 또는 SINGLE_IMAGE_MODE에서 `nil`
labels
label.text 라벨의 텍스트 설명입니다. TensorFlow Lite 모델의 메타데이터에 라벨 설명이 포함된 경우에만 반환됩니다.
label.index 분류 기준에서 지원하는 모든 라벨 중 라벨의 색인입니다.
label.confidence 객체 분류의 신뢰도 값입니다.

Swift

// objects contains one item if multiple object detection wasn't enabled.
for object in objects {
  let frame = object.frame
  let trackingID = object.trackingID
  let description = object.labels.enumerated().map { (index, label) in
    "Label \(index): \(label.text), \(label.confidence), \(label.index)"
  }.joined(separator: "\n")
}

Objective-C

// The list of detected objects contains one item if multiple object detection
// wasn't enabled.
for (MLKObject *object in objects) {
  CGRect frame = object.frame;
  NSNumber *trackingID = object.trackingID;
  for (MLKObjectLabel *label in object.labels) {
    NSString *labelString =
        [NSString stringWithFormat:@"%@, %f, %lu",
                                   label.text,
                                   label.confidence,
                                   (unsigned long)label.index];
  }
}

우수한 사용자 경험 보장

최상의 사용자 환경을 위해 앱에서 다음 가이드라인을 따르세요.

  • 객체 인식의 성공 여부는 객체의 시각적 복잡성에 따라 달라집니다. 시각적 특징이 적은 객체를 감지하려면 이미지에서 더 많은 부분을 차지해야 할 수 있습니다. 감지할 객체 종류에서 효과적인 입력 캡처에 대한 안내를 사용자에게 제공해야 합니다.
  • 분류를 사용할 때 지원되는 카테고리로 명확하게 분류되지 않는 객체를 감지하려면 알 수 없는 객체에 대한 특수 처리를 구현합니다.

[ML Kit Material Design 쇼케이스 앱][showcase-link]{: .external } 및 Material Design의 머신러닝 기반 기능 패턴 모음도 참고하세요.

성능 개선

실시간 애플리케이션에서 객체 감지를 사용하려는 경우 최상의 프레임 속도를 얻으려면 다음 안내를 따르세요.

  • 실시간 애플리케이션에서 스트리밍 모드를 사용할 때는 대부분의 기기가 적절한 프레임 속도를 생성할 수 없으므로 여러 객체 감지를 사용하지 마세요.

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