iOS용 이미지 분류 가이드

이미지 분류기 작업을 사용하면 이미지를 분류할 수 있습니다. 이때 정의된 카테고리 집합 중에서 이미지가 무엇을 나타내는지 식별하기 위해 살펴보겠습니다 이 안내에서는 iOS 앱 이 지침에서 설명하는 코드 샘플은 GitHub

이 작업의 예를 보려면 이 웹 데모를 참고하세요. 대상 애플리케이션의 기능, 모델, 구성 옵션에 대해 자세한 내용은 개요.

코드 예

MediaPipe 태스크 예시 코드는 이미지 분류기의 기본 구현입니다. 되었습니다. 이 예시에서는 실제 iOS 기기의 카메라를 사용하여 객체를 지속적으로 분류하고, 객체의 이미지와 동영상을 사용하여 기기 갤러리를 사용하여 객체를 정적으로 분류합니다.

이 앱을 자체 iOS 앱의 시작점으로 사용하거나 참고할 수 있습니다. 기존 앱을 수정할 때 이미지 분류 기준 예시 코드는 GitHub

코드 다운로드

다음 안내에서는 예시의 로컬 사본을 만드는 방법을 보여줍니다. git 명령줄 도구를 사용하여 코드를 실행합니다.

<ph type="x-smartling-placeholder">

예시 코드를 다운로드하려면 다음 안내를 따르세요.

  1. 다음 명령어를 사용하여 git 저장소를 클론합니다.

    git clone https://github.com/google-ai-edge/mediapipe-samples
    
  2. 원하는 경우 스파스 체크아웃을 사용하도록 git 인스턴스를 구성하여 다음과 같이 합니다. Image Classifier 예시 앱의 파일만 해당합니다.

    cd mediapipe
    git sparse-checkout init --cone
    git sparse-checkout set examples/image_classification/ios/
    

예시 코드의 로컬 버전을 생성한 후 MediaPipe 작업 라이브러리에서 Xcode를 사용하여 프로젝트를 열고 앱을 실행합니다. 대상 iOS 설정 가이드를 참조하세요.

주요 구성요소

다음 파일에는 이미지 분류기 예시의 중요 코드가 포함되어 있습니다. 애플리케이션:

설정

이 섹션에서는 개발 환경을 설정하는 주요 단계를 설명하고 코드 프로젝트를 사용하여 Image Classifier를 사용할 수 있습니다. 설정 방법에 대한 일반적인 정보는 MediaPipe 작업을 사용하기 위한 개발 환경(플랫폼 버전 포함) 요구사항에 대한 자세한 내용은 iOS 설정 가이드를 참고하세요.

<ph type="x-smartling-placeholder">

종속 항목

Image Classifier는 반드시 설치해야 하는 MediaPipeTasksVision 라이브러리를 사용합니다. CocoaPods를 사용하는 것입니다. Swift 및 Objective-C 앱 모두와 호환됩니다. 언어별 추가 설정이 필요하지 않습니다.

macOS에 CocoaPods를 설치하는 방법에 대한 안내는 CocoaPods 설치 가이드를 참조하세요. 필요한 포드로 Podfile를 만드는 방법에 대한 안내는 자세한 내용은 CocoaPods.

다음 코드를 사용하여 Podfile에 MediaPipeTasksVision 포드를 추가합니다.

target 'MyImageClassifierApp' do
  use_frameworks!
  pod 'MediaPipeTasksVision'
end

앱에 단위 테스트 타겟이 포함된 경우 Android 앱의 설정 가이드 iOS를 참고하세요. 내 Podfile

모델

MediaPipe 이미지 분류기 작업에는 호환되는 학습된 모델이 필요합니다. 살펴보겠습니다 Cloud Functions에 사용할 수 있는 학습된 모델에 대한 자세한 내용은 Image Classifier는 작업 개요를 참조하세요. 모델 섹션을 참조하세요.

모델을 선택 및 다운로드하고 Xcode를 사용하여 프로젝트 디렉터리에 추가합니다. Xcode 프로젝트에 파일을 추가하는 방법에 대한 안내는 관리 Xcode에서 파일 및 폴더 생성 프로젝트의 인스턴스입니다.

BaseOptions.modelAssetPath 속성을 사용하여 모델의 경로를 지정합니다. 합니다 코드 예는 다음 섹션을 참고하세요.

할 일 만들기

이니셜라이저 중 하나를 호출하여 Image Classifier 작업을 만들 수 있습니다. 이 ImageClassifier(options:) 이니셜라이저는 구성 옵션의 값을 설정합니다. 실행 모드, 표시 이름 언어, 최대 결과 수, 신뢰도 포함 차단 목록, 카테고리 허용 목록, 차단 목록입니다

맞춤설정된 구성으로 초기화된 이미지 분류기가 필요하지 않은 경우 ImageClassifier(modelPath:) 이니셜라이저를 사용하여 기본 옵션이 있는 Image Classifier 구성에 대한 자세한 내용은 옵션은 구성 개요를 참고하세요.

이미지 분류기 작업은 정지 이미지, 동영상 파일, 이렇게 세 가지 입력 데이터 유형을 지원합니다. 라이브 동영상 스트림이 포함됩니다 기본적으로 ImageClassifier(modelPath:)는 작업을 할 수 있습니다. 동영상을 처리하도록 작업을 초기화하려는 경우 파일 또는 라이브 동영상 스트림의 경우 ImageClassifier(options:)를 사용하여 동영상 또는 라이브 스트림 실행 모드 또한 라이브 스트림 모드를 사용하려면 추가 imageClassifierLiveStreamDelegate 구성 옵션 Image Classifier를 통해 이미지 분류 결과를 위임할 수 있습니다.

작업을 만드는 방법을 보려면 실행 모드에 해당하는 탭을 선택하세요. 추론을 실행합니다

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 작업의 실행 모드를 설정합니다. 세 가지 모드:

IMAGE: 단일 이미지 입력 모드입니다.

동영상: 동영상의 디코딩된 프레임 모드입니다.

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 구성 옵션 를 사용하면 분류 결과를 비동기식으로 전달할 수 있습니다. 이 델리게이트는 imageClassifier(_:didFinishClassification:timestampInMilliseconds:error:) 이 메서드는 분류를 처리한 후 Image Classifier가 호출합니다. 확인할 수 있습니다

옵션 이름 설명 값 범위 기본값
imageClassifierLiveStreamDelegate Image Classifier가 분류 결과를 비동기식으로 수신하도록 사용 설정합니다. 라이브 스트림 모드 인스턴스가 이 속성으로 설정된 클래스는 구현하고 imageClassifier(_:didFinishClassification:timestampInMilliseconds:error:) 메서드를 사용하여 축소하도록 요청합니다. 해당 사항 없음 설정되지 않음

데이터 준비

먼저 입력 이미지 또는 프레임을 MPImage 객체로 변환해야 합니다. 이미지 분류기로 전달합니다. MPImage에서는 다양한 유형의 iOS 이미지를 지원합니다. 추론을 위해 모든 실행 모드에서 사용할 수 있습니다. 자세한 내용은 MPImage에 대한 자세한 내용은 MPImage API

사용 사례와 실행 중인 모드에 따라 iOS 이미지 형식을 선택합니다. 필요합니다.MPImageUIImage, CVPixelBuffer 및 iOS 이미지 형식 CMSampleBuffer

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 방향을 설정할 수 있습니다. 지원되는 모든 API를 사용하여 MPImage를 초기화할 수 있습니다. UIImage.Orientation 값으로 사용됩니다. Image Classifier는 .upMirrored와 같이 미러링된 방향을 지원하지 않습니다. .downMirrored, .leftMirrored, .rightMirrored

UIImage에 대한 자세한 내용은 UIImage Apple 개발자 페이지를 참조하세요. 문서를 참조하세요.

CVPixelBuffer

CVPixelBuffer 형식은 프레임을 생성하는 애플리케이션에 적합 iOS CoreImage를 사용합니다. 프레임워크입니다

CVPixelBuffer 형식은 다음 실행 모드에 적합합니다.

  • 이미지: 일부 처리 후 CVPixelBuffer 이미지를 생성하는 앱 iOS의 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는 입력 이미지 또는 프레임이 있습니다.

다음 코드 샘플은 이미지 분류기를 실행하는 방법에 관한 기본 예를 보여줍니다. 실행할 수 있습니다

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:)입니다. 예시 코드를 사용하면 사용자가 원치 않는 처리 모드 간에 전환할 수 있습니다. 있습니다.

다음에 유의하세요.

  • 동영상 모드 또는 라이브 스트림 모드에서 실행하는 경우 Image Classifier 작업에 대한 입력 프레임의 타임스탬프입니다.

  • 이미지 또는 동영상 모드에서 실행할 때 이미지 분류 작업은 현재 스레드를 계속 대기시킵니다. 받는사람 현재 스레드를 차단하지 않고 백그라운드에서 처리를 실행합니다. iOS를 사용한 스레드 Dispatch 또는 NSOperation 살펴봤습니다

  • 라이브 스트림 모드에서 실행하면 이미지 분류기 작업이 즉시 반환됩니다. 현재 스레드를 차단하지 않습니다. 그러면 imageClassifier(_:didFinishClassification:timestampInMilliseconds:error:) 메서드를 사용하여 각 입력 프레임을 처리한 후 분류 결과를 바꿉니다. 이 Image Classifier는 전용 일련번호에서 이 메서드를 비동기식으로 호출합니다. 전달 큐에서 전달됩니다. 사용자 인터페이스에 결과를 표시하려면 기본 큐에 추가합니다. 만약 이미지 분류기 작업이 사용 중일 때 classifyAsync 함수가 호출됩니다. 다른 프레임을 처리하면 Image Classifier는 새 입력 프레임을 무시합니다.

결과 처리 및 표시

추론을 실행하면 Image Classifier 작업은 가능한 카테고리 목록이 포함된 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를 실행하여 얻은 것입니다. 날짜:

이미지 분류 기준 예시 코드는 분류를 표시하는 방법을 보여줍니다. 결과에 대한 자세한 내용은 코드 예 참조하세요.