이미지 분류기 통합

이미지 분류는 이미지, 이미지, 오디오, 동영상 등 나타냅니다. 예를 들어 어떤 종류의 동물이 나타나는지 알고자 할 수 있습니다. 예로 들 수 있습니다 이미지가 무엇을 나타내는지 예측하는 작업을 이미지 분류 이미지 분류기는 다양한 모델을 인식하도록 이미지 클래스입니다 예를 들어 모델은 사진을 인식하도록 학습시킬 수 있습니다. 는 토끼, 햄스터, 개의 세 가지 동물을 나타냅니다. 자세한 내용은 이미지 분류 예시 참조하세요.

Task Library ImageClassifier API를 사용하여 커스텀 이미지 배포 선행 학습된 분류 기준을 모바일 앱에 적용합니다.

ImageClassifier API의 주요 기능

  • 회전, 크기 조절, 색상 공간을 포함한 입력 이미지 처리 알 수 있습니다.

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

  • 라벨 지도 언어

  • 결과를 필터링하기 위한 점수 기준

  • Top-k 분류 결과입니다.

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

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

다음 모델은 ImageClassifier과(와) 호환됩니다. API에 액세스할 수 있습니다.

Java에서 추론 실행

자세한 내용은 이미지 분류 참조 앱 Android 앱에서 ImageClassifier를 사용하는 방법의 예를 확인하세요.

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

.tflite 모델 파일을 Android 모듈의 assets 디렉터리에 복사합니다. 지정할 수도 있습니다 파일을 압축하지 않도록 지정합니다. 모듈의 build.gradle 파일에 TensorFlow Lite 라이브러리를 추가합니다.

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

자세한 내용은 소스 코드와 javadoc을 ImageClassifier 구성 옵션을 참조하세요.

iOS에서 추론 실행

1단계: 종속 항목 설치

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

자세한 내용은 CocoaPods 가이드 Xcode 프로젝트에 포드를 추가하는 방법을 자세히 알아보세요.

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

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

추론에 사용할 .tflite 모델이 있는지 확인합니다. App Bundle을 개발합니다

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 구성 옵션을 참조하세요.

결과 예시

여기 보이는 것은 데이터 세트에서 BERT 분류기로 분할되었습니다.

참새

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-s로 TENSOR_AXIS_LABELS, 한 줄에 하나의 라벨 포함. 자세한 내용은 라벨 파일 예를 참고하세요. 이러한 첫 번째 AssociatedFile (있는 경우)은 label 필드를 채우는 데 사용됩니다. (C++에서는 class_name로 명명됨) display_name 필드 언어가 다음에서 사용된 ImageClassifierOptionsdisplay_names_locale 필드: 생성 시간(기본값: en, 예: 영어) 다음 중 어느 것도 해당되지 않는 경우 결과의 index 필드만 채워집니다.