이미지 세그먼트 통합

이미지 세그먼트 도구를 사용하면 이미지의 각 픽셀이 특정 클래스에 관해서도 알아보겠습니다. 이는 같은 위치에서 객체를 감지하는 객체 감지와는 직사각형 영역, 이미지 분류는 이미지 이미지 세분화 개요 보기 예 를 참조하세요.

Task Library ImageSegmenter API를 사용하여 커스텀 이미지 분류기 배포 모바일 앱에 적용할 수 있습니다

ImageSegmenter API의 주요 기능

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

  • 라벨 지도 언어

  • 두 가지 출력 유형, 카테고리 마스크와 신뢰도 마스크.

  • 표시용 색상 라벨입니다.

지원되는 이미지 세그먼트 도구 모델

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

Java에서 추론 실행

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

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
ImageSegmenterOptions options =
    ImageSegmenterOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setOutputType(OutputType.CONFIDENCE_MASK)
        .build();
ImageSegmenter imageSegmenter =
    ImageSegmenter.createFromFileAndOptions(context, modelFile, options);

// Run inference
List<Segmentation> results = imageSegmenter.segment(image);

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

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

let options = ImageSegmenterOptions(modelPath: modelPath)

// Configure any additional options:
// options.outputType = OutputType.confidenceMasks

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

// Run inference
let segmentationResult = try segmenter.segment(mlImage: mlImage)

Objective C

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

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

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

// Configure any additional options:
// options.outputType = TFLOutputTypeConfidenceMasks;

TFLImageSegmenter *segmenter = [TFLImageSegmenter imageSegmenterWithOptions:options
                                                                      error:nil];

// Convert the input image to MLImage.
UIImage *image = [UIImage imageNamed:@"plane.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
TFLSegmentationResult *segmentationResult =
    [segmenter segmentWithGMLImage:gmlImage error:nil];

출처 코드 TFLImageSegmenter 구성 옵션을 참조하세요.

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)
segmentation_options = processor.SegmentationOptions(
    output_type=processor.SegmentationOptions.output_type.CATEGORY_MASK)
options = vision.ImageSegmenterOptions(base_options=base_options, segmentation_options=segmentation_options)
segmenter = vision.ImageSegmenter.create_from_options(options)

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

# Run inference
image_file = vision.TensorImage.create_from_file(image_path)
segmentation_result = segmenter.segment(image_file)

출처 코드 ImageSegmenter 구성 옵션을 참조하세요.

C++에서 추론 실행

// Initialization
ImageSegmenterOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<ImageSegmenter> image_segmenter = ImageSegmenter::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 SegmentationResult result = image_segmenter->Segment(*frame_buffer).value();

출처 코드 ImageSegmenter 구성 옵션을 참조하세요.

결과 예시

이것은 세그먼테이션 결과의 예입니다. deeplab_v3 TensorFlow Hub에서 사용할 수 있는 일반 세분화 모델

비행기

Color Legend:
 (r: 000, g: 000, b: 000):
  index       : 0
  class name  : background
 (r: 128, g: 000, b: 000):
  index       : 1
  class name  : aeroplane

# (omitting multiple lines for conciseness) ...

 (r: 128, g: 192, b: 000):
  index       : 19
  class name  : train
 (r: 000, g: 064, b: 128):
  index       : 20
  class name  : tv
Tip: use a color picker on the output PNG file to inspect the output mask with
this legend.

세분화 카테고리 마스크는 다음과 같아야 합니다.

segmentation-output

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

모델 호환성 요구사항

ImageSegmenter API에는 필수 TFLite 모델이 포함된 TFLite 모델이 필요합니다. 메타데이터. 이미지 메타데이터 생성 예시 보기 TensorFlow Lite 메타데이터 작성기를 사용한 세그먼트 API를 참고하세요.

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

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

    • 크기가 [batch x mask_height x mask_width x num_classes]인 텐서, batch는 1이어야 하며, mask_widthmask_height는 모델이 생성한 세그먼테이션 마스크의 차원 num_classes는 모델에서 지원하는 클래스 수입니다.
    • 선택사항이지만 권장되는 라벨 맵은 유형 TENSOR_AXIS_LABELS인 AssociatedFile-s, 행입니다. 이러한 첫 번째 AssociatedFile (있는 경우)은 label를 채우는 데 사용됩니다. 필드 (C++에서는 class_name라고 함)를 반환합니다. display_name 필드는 언어가 다음에서 사용된 ImageSegmenterOptionsdisplay_names_locale 필드: 생성 시간(기본값: en, 예: 영어) 다음 중 어느 것도 해당되지 않는 경우 결과의 index 필드만 채워집니다.