Tích hợp bộ phân đoạn hình ảnh

Bộ phân đoạn hình ảnh dự đoán liệu mỗi pixel của hình ảnh có được liên kết với một lớp nhất định hay không. Điều này trái ngược với phát hiện đối tượng , phát hiện các đối tượng trong vùng hình chữ nhật và phân loại hình ảnh , phân loại hình ảnh tổng thể. Xem tổng quan về phân đoạn hình ảnh để biết thêm thông tin về trình phân đoạn hình ảnh.

Sử dụng API ImageSegmenter của Thư viện tác vụ để triển khai các trình phân đoạn hình ảnh tùy chỉnh hoặc các trình phân đoạn được đào tạo trước vào ứng dụng di động của bạn.

Các tính năng chính của API ImageSegmenter

  • Xử lý hình ảnh đầu vào, bao gồm xoay, thay đổi kích thước và chuyển đổi không gian màu.

  • Dán nhãn địa điểm bản đồ.

  • Hai loại đầu ra, mặt nạ danh mục và mặt nạ tự tin.

  • Nhãn màu cho mục đích hiển thị.

Các mô hình phân đoạn hình ảnh được hỗ trợ

Các mô hình sau được đảm bảo tương thích với API ImageSegmenter .

Chạy suy luận trong Java

Xem ứng dụng tham khảo Phân đoạn hình ảnh để biết ví dụ về cách sử dụng ImageSegmenter trong ứng dụng Android.

Bước 1: Nhập phần phụ thuộc Gradle và các cài đặt khác

Sao chép tệp mô hình .tflite vào thư mục nội dung của mô-đun Android nơi mô hình sẽ được chạy. Chỉ định rằng tệp sẽ không được nén và thêm thư viện TensorFlow Lite vào tệp build.gradle của mô-đun:

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 (NNAPI is included)
    implementation 'org.tensorflow:tensorflow-lite-task-vision'
    // Import the GPU delegate plugin Library for GPU inference
    implementation 'org.tensorflow:tensorflow-lite-gpu-delegate-plugin'
}

Bước 2: Sử dụng mô hình

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

Xem mã nguồn và javadoc để có thêm tùy chọn cấu hình ImageSegmenter .

Chạy suy luận trong iOS

Bước 1: Cài đặt các phụ thuộc

Thư viện tác vụ hỗ trợ cài đặt bằng CocoaPods. Đảm bảo rằng CocoaPods đã được cài đặt trên hệ thống của bạn. Vui lòng xem hướng dẫn cài đặt CocoaPods để được hướng dẫn.

Vui lòng xem hướng dẫn của CocoaPods để biết chi tiết về cách thêm nhóm vào dự án Xcode.

Thêm nhóm TensorFlowLiteTaskVision vào Podfile.

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

Đảm bảo rằng mô hình .tflite bạn sẽ sử dụng để suy luận có trong gói ứng dụng của bạn.

Bước 2: Sử dụng mô hình

Nhanh

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

Mục tiêu 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];

Xem mã nguồn để biết thêm tùy chọn cấu hình TFLImageSegmenter .

Chạy suy luận trong Python

Bước 1: Cài đặt gói pip

pip install tflite-support

Bước 2: Sử dụng mô hình

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

Xem mã nguồn để biết thêm tùy chọn cấu hình ImageSegmenter .

Chạy suy luận trong 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();

Xem mã nguồn để biết thêm tùy chọn cấu hình ImageSegmenter .

Kết quả ví dụ

Dưới đây là ví dụ về kết quả phân đoạn của deeplab_v3 , một mô hình phân đoạn chung có sẵn trên TensorFlow Hub.

máy bay

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.

Mặt nạ danh mục phân đoạn sẽ trông như sau:

phân đoạn-đầu ra

Hãy dùng thử công cụ demo CLI đơn giản dành cho ImageSegmenter bằng mô hình và dữ liệu thử nghiệm của riêng bạn.

Yêu cầu tương thích mô hình

API ImageSegmenter yêu cầu mô hình TFLite với Siêu dữ liệu mô hình TFLite bắt buộc. Xem ví dụ về cách tạo siêu dữ liệu cho trình phân đoạn hình ảnh bằng API Trình ghi siêu dữ liệu TensorFlow Lite .

  • Tenxơ hình ảnh đầu vào (kTfLiteUInt8/kTfLiteFloat32)

    • hình ảnh đầu vào có kích thước [batch x height x width x channels] .
    • suy luận hàng loạt không được hỗ trợ ( batch buộc phải là 1).
    • chỉ hỗ trợ đầu vào RGB ( channels bắt buộc phải là 3).
    • nếu loại là kTfLiteFloat32 thì bắt buộc phải đính kèm NormalizationOptions vào siêu dữ liệu để chuẩn hóa đầu vào.
  • Tenor mặt nạ đầu ra: (kTfLiteUInt8/kTfLiteFloat32)

    • tensor có kích thước [batch x mask_height x mask_width x num_classes] , trong đó batch bắt buộc phải bằng 1, mask_widthmask_height là kích thước của mặt nạ phân đoạn do mô hình tạo ra và num_classes là số lượng lớp được mô hình hỗ trợ.
    • (các) bản đồ nhãn tùy chọn (nhưng được khuyến nghị) có thể được đính kèm dưới dạng các AssociatedFile-s với loại TENSOR_AXIS_LABELS, chứa một nhãn trên mỗi dòng. Tệp liên kết đầu tiên (nếu có) được sử dụng để điền vào trường label (được đặt tên là class_name trong C++) của kết quả. Trường display_name được điền từ AssociatedFile (nếu có) có ngôn ngữ khớp với trường display_names_locale của ImageSegmenterOptions được sử dụng tại thời điểm tạo ("en" theo mặc định, tức là tiếng Anh). Nếu không có sẵn những thứ này thì chỉ có trường index của kết quả sẽ được điền.