整合圖片分類器

圖片分類是機器學習的常見用途 圖片呈現方式舉例來說,我們可能會想知道 出現的動物類型 指定相片中的人物這項任務是指預測圖片所代表的意義 圖片分類。圖片分類器經過訓練,可辨識各種可能性 圖片種類。舉例來說,我們可能會用經過訓練的模型 代表三種不同的動物:兔子、倉鼠和狗。詳情請見 這個 圖片分類範例 ,進一步瞭解圖片分類器

使用工作程式庫 ImageClassifier API 部署自訂映像檔 將分類器或預先訓練的分類器納入行動應用程式

ImageClassifier API 的主要功能

  • 輸入圖片處理作業,包括旋轉、調整大小和色域 轉換率

  • 輸入圖片的搜尋目標區域。

  • 標籤對應語言代碼。

  • 用來篩選結果的分數門檻。

  • 「前 K 個」分類結果。

  • 標籤許可清單和拒絕清單。

支援的圖片分類器模型

下列型號保證與 ImageClassifier 相容 也能使用 Google Cloud CLI 或 Compute Engine API

在 Java 中執行推論

詳情請參閱 圖片分類參考應用程式 查看範例,瞭解如何在 Android 應用程式中使用 ImageClassifier

步驟 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

在 Podfile 中新增 TensorFlowLiteTaskVision Pod。

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

確認您要用於推論的 .tflite 模型出現在 您的應用程式套件。

步驟 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

試試簡易設計 ImageClassifier 的 CLI 示範工具 使用自己的模型與測試資料

模型相容性需求

ImageClassifier API 預期的 TFLite 模型必須具有 TFLite 模型中繼資料。 查看使用 TensorFlow Lite Metadata Writer API

相容的圖片分類器模型必須符合下列規定:

  • 輸入圖片張量 (kTfLiteUInt8/kTfLiteFloat32)

    • 輸入大小為 [batch x height x width x channels] 的圖片。
    • 不支援批次推論 (batch 須為 1)。
    • 僅支援 RGB 輸入 (channels 必須為 3)。
    • 如果型別是 kTfLiteFloat32,就必須使用正規化選項 附加於中繼資料,以便進行輸入正規化
  • 輸出分數張量 (kTfLiteUInt8/kTfLiteFloat32)

    • 含有 N 類別和 2 或 4 個維度,即 [1 x N][1 x 1 x 1 x N]
    • 選用 (但建議使用) 將對應標籤對應為 AssociatedFile-s 和 type TENSOR_AXIS_LABELS,每行一個標籤。詳情請參閱 標籤檔案範例。 這個 AssociatedFile (如有) 會填入 label 欄位 (在 C++ 中稱為 class_name) 的結果。display_name 欄位 填入關聯檔案 (如有),其語言代碼符合 使用的 ImageClassifierOptionsdisplay_names_locale 欄位 建立時間 (預設為「en」,例如英文)。如果這些都不是 可用,只有結果的 index 欄位會填入內容。