שילוב של מקטעי תמונות

באמצעות מקטעי תמונות, הם חוזים אם כל פיקסל בתמונה משויך סיווג מסוים. זאת בניגוד לזיהוי אובייקטים, שמזהה אובייקטים מלבניים וסיווג תמונות, שמדרגים את כל תמונה. סקירה כללית על פילוח תמונות דוגמה לקבלת מידע נוסף על פלחים של תמונות.

להשתמש ב-API של ספריית המשימות ImageSegmenter כדי לפרוס את מקטעי התמונות בהתאמה אישית או כאלה שעברו אימון מראש לאפליקציות שלכם לנייד.

תכונות מרכזיות של Imagesegmenter API

  • עיבוד תמונות קלט, כולל סיבוב, שינוי גודל ומרחב צבעים להמרה.

  • הוספת תווית ללוקאל במפה.

  • שני סוגי פלט: מסכת קטגוריה ומסכות אבטחה.

  • תווית צבעונית למטרות תצוגה.

מודלים נתמכים של פילוחי תמונות

מובטח שהמודלים הבאים יתאימו לImageSegmenter API.

הרצת ההסקה ב-Java

מידע נוסף זמין בחומר העזר בנושא פילוח תמונות אפליקציה דוגמה לאופן השימוש ב-ImageSegmenter באפליקציה ל-Android.

שלב 1: מייבאים תלות ב-Gradle והגדרות אחרות

מעתיקים את קובץ המודל .tflite לספריית הנכסים הדיגיטליים של מודול Android. שבה המודל יפעל. לציין שאין לדחוס את הקובץ. מוסיפים את ספריית 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);

צפייה בקוד המקור Javadoc לאפשרויות נוספות להגדרה של ImageSegmenter.

הרצת ההסקה ב-iOS

שלב 1: מתקינים את יחסי התלות

ספריית המשימות תומכת בהתקנה באמצעות CocoaPods. צריך לוודא ש-CocoaPods מותקנת במערכת שלך. לפרטים נוספים, ניתן לעיין בהתקנת CocoaPods מדריך לקבלת הוראות.

מומלץ לעיין ב-CocoaPods מדריך מפורט הוספת Pods לפרויקט Xcode.

מוסיפים את ה-Pod TensorFlowLiteTaskVision בקובץ ה-Podfile.

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 את המודל ונתוני הבדיקה שלכם.

דרישות התאימות של המודלים

ה-API ImageSegmenter מצפה למודל TFLite עם מודל TFLite חובה מטא-נתונים. דוגמאות ליצירת מטא-נתונים של תמונה משתמשים ב-TensorFlow Lite Metadata Writer API.

  • קלט תמונה tensor (kTfLiteUInt8/kTfLiteFloat32)

    • קלט תמונה בגודל [batch x height x width x channels].
    • אין תמיכה בהֶקֵּשׁ מנתונים מרובים (הפונקציה batch חייבת להיות 1).
    • יש תמיכה רק בקלט RGB (הערך channels חייב להיות 3).
    • אם הסוג הוא kTfLiteFloat32, יש צורך ב-regularizationOptions מצורפים למטא-נתונים לצורך נירמול הקלט.
  • טנזור מסכות פלט: (kTfLiteUInt8/kTfLiteFloat32)

    • את Tensor בגודל [batch x mask_height x mask_width x num_classes], כאשר הערך batch חייב להיות 1, הערך mask_width ו-mask_height הם הערכים של מסכות הפילוח שהמודל יצר, num_classes הוא מספר המחלקות שנתמכות במודל.
    • ניתן לצרף מפות תוויות אופציונליות (אבל מומלצות) בתור AssociatedFile-s עם סוג TENSOR_AXIS_Labels, המכילה תווית אחת לכל השורה הזו. ה-AssociatedFile הראשון (אם יש כזה) משמש למילוי השדה label (נקרא כ-class_name ב-C++ ) של התוצאות. display_name ימולאו מה-AssociatedFile (אם יש) שהלוקאל שלו תואם השדה display_names_locale של ImageSegmenterOptions שנמצא בשימוש בזמן היצירה ('en' כברירת מחדל, כלומר באנגלית). אם אף אחת מהאפשרויות האלה זמין, רק השדה index של התוצאות ימולא.