שילוב מסווגי תמונות

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

משתמשים ב-API של ספריית המשימות ImageClassifier כדי לפרוס את התמונה המותאמת אישית של מסווגים או סיווגים שאומנו מראש לאפליקציות שלך לנייד.

תכונות מרכזיות ב-ImageClassifier API

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

  • אזור העניין של תמונת הקלט.

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

  • סף הציון לסינון התוצאות.

  • תוצאות סיווג מובילות.

  • רשימת היתרים ורשימת ישויות שנחסמו.

מודלים נתמכים של מסווגי תמונות

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

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

לצפייה אפליקציית עזר לסיווג תמונות דוגמה לאופן השימוש ב-ImageClassifier באפליקציה ל-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
ImageClassifierOptions options =
    ImageClassifierOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setMaxResults(1)
        .build();
ImageClassifier imageClassifier =
    ImageClassifier.createFromFileAndOptions(
        context, modelFile, options);

// Run inference
List<Classifications> results = imageClassifier.classify(image);

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

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

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

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

כדאי לעיין מדריך CocoaPods עבור על הוספת רצפי מודעות לפרויקט 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: "birds_V1",
                                            ofType: "tflite") else { return }

let options = ImageClassifierOptions(modelPath: modelPath)

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

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

// Run inference
let classificationResults = try classifier.classify(mlImage: mlImage)

Objective C

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

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

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

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

TFLImageClassifier *classifier = [TFLImageClassifier imageClassifierWithOptions:options
                                                                          error:nil];

// Convert the input image to MLImage.
UIImage *image = [UIImage imageNamed:@"sparrow.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
TFLClassificationResult *classificationResult =
    [classifier classifyWithGMLImage:gmlImage error:nil];

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

הרצת ההסקה ב-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)
classification_options = processor.ClassificationOptions(max_results=2)
options = vision.ImageClassifierOptions(base_options=base_options, classification_options=classification_options)
classifier = vision.ImageClassifier.create_from_options(options)

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

# Run inference
image = vision.TensorImage.create_from_file(image_path)
classification_result = classifier.classify(image)

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

הרצת ההסקה ב-C++

// Initialization
ImageClassifierOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<ImageClassifier> image_classifier = ImageClassifier::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 ClassificationResult result = image_classifier->Classify(*frame_buffer).value();

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

תוצאות לדוגמה

לפניכם דוגמה לתוצאות הסיווג של סיווג ציפורים.

דרור

Results:
  Rank #0:
   index       : 671
   score       : 0.91406
   class name  : /m/01bwb9
   display name: Passer domesticus
  Rank #1:
   index       : 670
   score       : 0.00391
   class name  : /m/01bwbt
   display name: Passer montanus
  Rank #2:
   index       : 495
   score       : 0.00391
   class name  : /m/0bwm6m
   display name: Passer italiae

תנסו את השיטה הפשוטה כלי ההדגמה של CLI ל-ImageClassifier את המודל ונתוני הבדיקה שלכם.

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

ל-API ImageClassifier נדרש מודל 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)

    • עם N מחלקות או 2 או 4 מאפיינים, כלומר [1 x N] או [1 x 1 x 1 x N]
    • מיפויי תוויות אופציונליים (אבל מומלצים) כ-AssociatedFile-s עם סוג TENSOR_AXIS_Labels, מכילה תווית אחת בכל שורה. לצפייה קובץ תווית לדוגמה. ה-AssociatedFile הראשון (אם יש כזה) משמש למילוי השדה label (נקראים בשם class_name ב-C++ ) של התוצאות. השדה display_name מולא מה-AssociatedFile (אם יש) שהלוקאל שלו תואם השדה display_names_locale של ה-ImageClassifierOptions שנמצא בשימוש בזמן היצירה ('en' כברירת מחדל, כלומר באנגלית). אם אף אחת מהאפשרויות האלה זמין, רק השדה index של התוצאות ימולא.