이미지 분류기 통합

이미지 분류는 머신러닝을 사용하여 이미지가 나타내는 대상을 식별하는 일반적인 방법입니다. 예를 들어 특정 사진에 어떤 유형의 동물이 표시되는지 알고 싶을 수 있습니다. 이미지가 나타내는 내용을 예측하는 작업을 이미지 분류라고 합니다. 이미지 분류기는 다양한 이미지 클래스를 인식하도록 학습됩니다. 예를 들어 토끼, 햄스터, 개의 세 가지 동물 유형을 나타내는 사진을 인식하도록 모델을 학습시킬 수 있습니다. 이미지 분류기에 관한 자세한 내용은 이미지 분류 예시를 참고하세요.

작업 라이브러리 ImageClassifier API를 사용하여 맞춤 이미지 분류기 또는 사전 학습된 분류기를 모바일 앱에 배포합니다.

ImageClassifier API의 주요 기능

  • 회전, 크기 조절, 색상 공간 변환을 비롯한 입력 이미지 처리

  • 입력 이미지의 관심 영역입니다.

  • 지도 언어 라벨

  • 결과를 필터링할 점수 기준입니다.

  • 상위 k 분류 결과입니다.

  • 라벨 허용 목록 및 차단 목록

지원되는 이미지 분류기 모델

다음 모델은 ImageClassifier API와 호환됩니다.

Java에서 추론 실행

Android 앱에서 ImageClassifier를 사용하는 방법의 예시는 이미지 분류 참조 앱을 참고하세요.

1단계: Gradle 종속 항목 및 기타 설정 가져오기

모델이 실행될 Android 모듈의 애셋 디렉터리에 .tflite 모델 파일을 복사합니다. 파일을 압축하지 않도록 지정하고 TensorFlow Lite 라이브러리를 모듈의 build.gradle 파일에 추가합니다.

android {
    // Other settings

    // Specify tflite file should not be compressed for the app apk
    aaptOptions {
        noCompress "tflite"
    }
}

dependencies {
    // Other dependencies

    // Import the Task Vision Library dependency
    implementation 'org.tensorflow:tensorflow-lite-task-vision'
    // Import the GPU delegate plugin Library for GPU inference
    implementation 'org.tensorflow:tensorflow-lite-gpu-delegate-plugin'
}

2단계: 모델 사용

// Initialization
ImageClassifierOptions options =
    ImageClassifierOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setMaxResults(1)
        .build();
ImageClassifier imageClassifier =
    ImageClassifier.createFromFileAndOptions(
        context, modelFile, options);

// Run inference
List<Classifications> results = imageClassifier.classify(image);

ImageClassifier를 구성하는 추가 옵션은 소스 코드 및 javadoc을 참고하세요.

iOS에서 추론 실행

1단계: 종속 항목 설치

작업 라이브러리는 CocoaPods를 사용한 설치를 지원합니다. 시스템에 CocoaPods가 설치되어 있는지 확인합니다. 자세한 내용은 CocoaPods 설치 가이드를 참고하세요.

Xcode 프로젝트에 포드를 추가하는 방법에 관한 자세한 내용은 CocoaPods 가이드를 참고하세요.

Podfile에 TensorFlowLiteTaskVision 포드를 추가합니다.

target 'MyAppWithTaskAPI' do
  use_frameworks!
  pod 'TensorFlowLiteTaskVision'
end

추론에 사용할 .tflite 모델이 앱 번들에 있는지 확인합니다.

2단계: 모델 사용

Swift

// Imports
import TensorFlowLiteTaskVision

// Initialization
guard let modelPath = Bundle.main.path(forResource: "birds_V1",
                                            ofType: "tflite") else { return }

let options = ImageClassifierOptions(modelPath: modelPath)

// Configure any additional options:
// options.classificationOptions.maxResults = 3

let classifier = try ImageClassifier.classifier(options: options)

// Convert the input image to MLImage.
// There are other sources for MLImage. For more details, please see:
// https://developers.google.com/ml-kit/reference/ios/mlimage/api/reference/Classes/GMLImage
guard let image = UIImage (named: "sparrow.jpg"), let mlImage = MLImage(image: image) else { return }

// Run inference
let classificationResults = try classifier.classify(mlImage: mlImage)

Objective-C

// Imports
#import <TensorFlowLiteTaskVision/TensorFlowLiteTaskVision.h>

// Initialization
NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"birds_V1" ofType:@"tflite"];

TFLImageClassifierOptions *options =
    [[TFLImageClassifierOptions alloc] initWithModelPath:modelPath];

// Configure any additional options:
// options.classificationOptions.maxResults = 3;

TFLImageClassifier *classifier = [TFLImageClassifier imageClassifierWithOptions:options
                                                                          error:nil];

// Convert the input image to MLImage.
UIImage *image = [UIImage imageNamed:@"sparrow.jpg"];

// There are other sources for GMLImage. For more details, please see:
// https://developers.google.com/ml-kit/reference/ios/mlimage/api/reference/Classes/GMLImage
GMLImage *gmlImage = [[GMLImage alloc] initWithImage:image];

// Run inference
TFLClassificationResult *classificationResult =
    [classifier classifyWithGMLImage:gmlImage error:nil];

TFLImageClassifier를 구성하는 추가 옵션은 소스 코드를 참고하세요.

Python에서 추론 실행

1단계: pip 패키지 설치

pip install tflite-support

2단계: 모델 사용

# Imports
from tflite_support.task import vision
from tflite_support.task import core
from tflite_support.task import processor

# Initialization
base_options = core.BaseOptions(file_name=model_path)
classification_options = processor.ClassificationOptions(max_results=2)
options = vision.ImageClassifierOptions(base_options=base_options, classification_options=classification_options)
classifier = vision.ImageClassifier.create_from_options(options)

# Alternatively, you can create an image classifier in the following manner:
# classifier = vision.ImageClassifier.create_from_file(model_path)

# Run inference
image = vision.TensorImage.create_from_file(image_path)
classification_result = classifier.classify(image)

ImageClassifier를 구성하는 추가 옵션은 소스 코드를 참고하세요.

C++에서 추론 실행

// Initialization
ImageClassifierOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<ImageClassifier> image_classifier = ImageClassifier::CreateFromOptions(options).value();

// Create input frame_buffer from your inputs, `image_data` and `image_dimension`.
// See more information here: tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h

std::unique_ptr<FrameBuffer> frame_buffer = CreateFromRgbRawBuffer(
      image_data, image_dimension);

// Run inference
const ClassificationResult result = image_classifier->Classify(*frame_buffer).value();

ImageClassifier를 구성하는 추가 옵션은 소스 코드를 참고하세요.

결과 예시

다음은 새 분류기의 분류 결과의 예입니다.

참새

Results:
  Rank #0:
   index       : 671
   score       : 0.91406
   class name  : /m/01bwb9
   display name: Passer domesticus
  Rank #1:
   index       : 670
   score       : 0.00391
   class name  : /m/01bwbt
   display name: Passer montanus
  Rank #2:
   index       : 495
   score       : 0.00391
   class name  : /m/0bwm6m
   display name: Passer italiae

자체 모델과 테스트 데이터로 간단한 ImageClassifier용 CLI 데모 도구를 사용해 보세요.

모델 호환성 요구사항

ImageClassifier API는 필수 TFLite 모델 메타데이터가 있는 TFLite 모델을 예상합니다. TensorFlow Lite Metadata Writer API를 사용하여 이미지 분류기의 메타데이터를 만드는 예를 참고하세요.

호환되는 이미지 분류기 모델은 다음 요구사항을 충족해야 합니다.

  • 입력 이미지 텐서 (kTfLiteUInt8/kTfLiteFloat32)

    • [batch x height x width x channels] 크기의 이미지 입력
    • 일괄 추론은 지원되지 않습니다 (batch이 1이어야 함).
    • RGB 입력만 지원됩니다 (channels은 3이어야 함).
    • 유형이 kTfLiteFloat32인 경우 입력 정규화의 메타데이터에 NormalizationOptions를 연결해야 합니다.
  • 출력 점수 텐서 (kTfLiteUInt8/kTfLiteFloat32)

    • N 클래스와 2개 또는 4개의 측정기준([1 x N] 또는 [1 x 1 x 1 x N])
    • 선택사항 (권장) 라벨 맵(AssociatedFile)으로, 유형은 TENSOR_AXIS_LABELS이며 각 줄에 하나의 라벨이 포함됩니다. 예시 라벨 파일을 참고하세요. 이러한 첫 번째 AssociatedFile (있는 경우)은 결과의 label 필드(C++에서는 class_name로 명명됨)를 채우는 데 사용됩니다. display_name 필드는 생성 시 사용된 ImageClassifierOptionsdisplay_names_locale 필드와 로케일이 일치하는 AssociatedFile (있는 경우)에서 채워집니다 ('en', 즉 영어, 기본값). 이러한 항목이 모두 제공되지 않으면 결과의 index 필드만 채워집니다.