이미지 세그멘터는 이미지의 각 픽셀이 특정 클래스와 연결되어 있는지 예측합니다. 이는 사각형 영역에서 객체를 감지하는 객체 감지 및 전체 이미지를 분류하는 이미지 분류와는 대조적입니다. 이미지 세그멘테이터에 관한 자세한 내용은 이미지 세그멘테이션 개요 예시를 참고하세요.
작업 라이브러리 ImageSegmenter API를 사용하여 맞춤 이미지 세그멘테이션 도구나 사전 학습된 세그멘테이션 도구를 모바일 앱에 배포합니다.
ImageSegmenter API의 주요 기능
회전, 크기 조절, 색상 공간 변환을 비롯한 입력 이미지 처리
지도 언어 라벨
두 가지 출력 유형(카테고리 마스크 및 신뢰도 마스크)
표시 목적으로 사용되는 색상이 지정된 라벨입니다.
지원되는 이미지 세그멘테이션 모델
다음 모델은 ImageSegmenter API와 호환됩니다.
모델 호환성 요구사항을 충족하는 맞춤 모델
Java에서 추론 실행
Android 앱에서 ImageSegmenter를 사용하는 방법의 예는 이미지 세분화 참조 앱을 참고하세요.
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
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);
ImageSegmenter를 구성하는 추가 옵션은 소스 코드 및 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: "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를 구성하는 추가 옵션은 소스 코드를 참고하세요.
결과 예시
다음은 TensorFlow Hub에서 사용할 수 있는 일반 분할 모델인 deeplab_v3의 분할 결과의 예입니다.

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.
분할 카테고리 마스크는 다음과 같이 표시됩니다.

자체 모델과 테스트 데이터로 간단한 ImageSegmenter용 CLI 데모 도구를 사용해 보세요.
모델 호환성 요구사항
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_width와mask_height는 모델에서 생성된 분할 마스크의 차원이며,num_classes은 모델에서 지원하는 클래스 수입니다. - 선택사항(권장) 라벨 맵은 AssociatedFile로 연결할 수 있으며, 유형은 TENSOR_AXIS_LABELS이고 각 줄에 하나의 라벨이 포함됩니다. 이러한 AssociatedFile 중 첫 번째 항목 (있는 경우)은 결과의
label필드 (C++에서는class_name로 명명됨)를 채우는 데 사용됩니다.display_name필드는 생성 시간에 사용된ImageSegmenterOptions의display_names_locale필드와 언어가 일치하는 AssociatedFile (있는 경우)에서 채워집니다 ('en', 즉 영어로 기본 설정됨). 이러한 항목이 모두 제공되지 않으면 결과의index필드만 채워집니다.
- 크기가