객체 감지기 통합

객체 감지기로 알려진 객체 집합 중 어떤 것이 있을 수 있는지 식별할 수 있습니다. 주어진 이미지나 동영상 내에서의 위치에 관한 정보를 제공합니다. 있습니다. 객체 감지기는 특정 물건의 존재와 위치를 객체를 생성할 수 있습니다. 예를 들어 모델은 이미지로 학습될 수 있습니다. 여러 과일을 포함하는 라벨과 함께 나타내는 과일 분류 (예: 사과, 바나나, 딸기) 이미지에서 각 객체가 나타나는 위치를 지정하는 데이터입니다. 자세한 내용은 객체 감지 예시 참조하세요.

Task Library ObjectDetector API를 사용하여 커스텀 객체 감지기 배포 모바일 앱에 적용할 수 있습니다

ObjectDetector API의 주요 특징

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

  • 라벨 지도 언어

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

  • Top-k 감지 결과입니다.

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

지원되는 객체 감지기 모델

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

Java에서 추론 실행

자세한 내용은 객체 감지 참조 앱 Android 앱에서 ObjectDetector를 사용하는 방법의 예를 확인하세요.

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
ObjectDetectorOptions options =
    ObjectDetectorOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setMaxResults(1)
        .build();
ObjectDetector objectDetector =
    ObjectDetector.createFromFileAndOptions(
        context, modelFile, options);

// Run inference
List<Detection> results = objectDetector.detect(image);

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

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: "ssd_mobilenet_v1",
                                            ofType: "tflite") else { return }

let options = ObjectDetectorOptions(modelPath: modelPath)

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

let detector = try ObjectDetector.detector(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: "cats_and_dogs.jpg"), let mlImage = MLImage(image: image) else { return }

// Run inference
let detectionResult = try detector.detect(mlImage: mlImage)

Objective-C

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

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

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

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

TFLObjectDetector *detector = [TFLObjectDetector objectDetectorWithOptions:options
                                                                     error:nil];

// Convert the input image to MLImage.
UIImage *image = [UIImage imageNamed:@"dogs.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
TFLDetectionResult *detectionResult = [detector detectWithGMLImage:gmlImage error:nil];

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

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)
detection_options = processor.DetectionOptions(max_results=2)
options = vision.ObjectDetectorOptions(base_options=base_options, detection_options=detection_options)
detector = vision.ObjectDetector.create_from_options(options)

# Alternatively, you can create an object detector in the following manner:
# detector = vision.ObjectDetector.create_from_file(model_path)

# Run inference
image = vision.TensorImage.create_from_file(image_path)
detection_result = detector.detect(image)

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

C++에서 추론 실행

// Initialization
ObjectDetectorOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<ObjectDetector> object_detector = ObjectDetector::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 DetectionResult result = object_detector->Detect(*frame_buffer).value();

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

결과 예시

이것은 다음 예와 같이 ssd mobilenet v1 확인할 수 있습니다

개

Results:
 Detection #0 (red):
  Box: (x: 355, y: 133, w: 190, h: 206)
  Top-1 class:
   index       : 17
   score       : 0.73828
   class name  : dog
 Detection #1 (green):
  Box: (x: 103, y: 15, w: 138, h: 369)
  Top-1 class:
   index       : 17
   score       : 0.73047
   class name  : dog

입력 이미지에 경계 상자를 렌더링합니다.

감지 출력

간단한 ObjectDetector용 CLI 데모 도구 모델을 학습시킬 수 있습니다

모델 호환성 요구사항

ObjectDetector API에는 필수가 포함된 TFLite 모델이 필요합니다. TFLite 모델 메타데이터. 생성 예시 보기 다음 객체를 사용하는 객체 감지기의 메타데이터입니다. TensorFlow Lite Metadata Writer API.

호환되는 객체 감지기 모델은 다음 요구사항을 충족해야 합니다.

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

    • 크기가 [batch x height x width x channels]인 이미지 입력
    • 일괄 추론은 지원되지 않습니다 (batch는 1이어야 함).
    • RGB 입력만 지원됩니다 (channels는 3이어야 함).
    • 유형이 kTfLiteFloat32인 경우 NormalizationOptions가 입력 정규화를 위해 메타데이터에 첨부됩니다.
  • 출력 텐서는 DetectionPostProcess 작업의 출력 4개여야 합니다.예:

    • 위치 텐서 (kTfLiteFloat32) <ph type="x-smartling-placeholder">
        </ph>
      • 크기가 [1 x num_results x 4]인 텐서로, 다음을 나타내는 내부 배열입니다. [상단, 왼쪽, 오른쪽, 하단] 형식으로 입력합니다.
      • 메타데이터에 BoundingBoxProperties를 연결해야 합니다. type=BOUNDARIES 및 `Coordinate_type=RATIO를 지정해야 합니다.
    • 클래스 텐서 (kTfLiteFloat32)

      • 크기가 [1 x num_results]인 텐서로, 각 값은 클래스의 정수 색인입니다.
      • 선택사항이지만 권장되는 라벨 맵은 TENSOR_VALUE_LABELS 유형의 AssociatedFile-s, 라벨 1개가 포함되어 있음 한 줄에 하나씩 입력합니다. 자세한 내용은 라벨 파일 예를 참고하세요. 이러한 첫 번째 AssociatedFile (있는 경우)은 결과의 class_name 필드입니다. display_name 필드는 다음과 같습니다. 언어가 다음에서 사용된 ObjectDetectorOptionsdisplay_names_locale 필드: 생성 시간(기본값: en, 예: 영어) 다음 중 어느 것도 해당되지 않는 경우 결과의 index 필드만 채워집니다.
    • 점수 텐서 (kTfLiteFloat32)

      • 크기가 [1 x num_results]인 텐서로, 각 값은 인코더-디코더입니다.
    • 감지 텐서 수 (kTfLiteFloat32)

      • 정수 num_results를 크기가 [1]인 텐서로 표현합니다.