圖片分類是機器學習的常見用途,可識別圖片內容。舉例來說,我們可能想知道特定圖片中出現的動物類型。預測圖片內容的工作稱為「圖片分類」。圖片分類器經過訓練,可辨識各種圖片類別。舉例來說,模型可能會經過訓練,辨識代表三種不同動物的相片:兔子、倉鼠和狗。如要進一步瞭解圖片分類器,請參閱圖片分類範例。
使用 Task Library ImageClassifier API,將自訂或預先訓練的圖片分類器部署到行動應用程式中。
ImageClassifier API 的主要功能
處理輸入圖片,包括旋轉、調整大小和轉換色彩空間。
輸入圖片的感興趣區域。
標記地圖語言區域。
篩選結果的分數門檻。
前 k 項分類結果。
標籤許可清單和拒絕清單。
支援的圖片分類模型
下列機型保證與 ImageClassifier
API 相容。
使用 TensorFlow Lite Model Maker for Image Classification 建立的模型。
AutoML Vision Edge 圖片分類建立的模型。
符合模型相容性規定的自訂模型。
在 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);
如要瞭解設定 ImageClassifier 的其他選項,請參閱原始碼和 Javadoc。
在 iOS 中執行推論
步驟 1:安裝依附元件
工作程式庫支援使用 CocoaPods 安裝。請確認系統已安裝 CocoaPods。如需操作說明,請參閱 CocoaPods 安裝指南。
如要瞭解如何將 Pod 新增至 Xcode 專案,請參閱 CocoaPods 指南。
在 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,則必須將 NormalizationOptions 附加至中繼資料,以進行輸入正規化。
- 大小為
輸出分數張量 (kTfLiteUInt8/kTfLiteFloat32)
- ,以及 2 個或 4 個維度,也就是
[1 x N]或[1 x 1 x 1 x N]N - 選用 (但建議使用) 標籤對應檔,以 AssociatedFile 形式提供,類型為 TENSOR_AXIS_LABELS,每行包含一個標籤。請參閱標籤檔案範例。系統會使用第一個這類 AssociatedFile (如有) 填入結果的
label欄位 (在 C++ 中命名為class_name)。系統會從 AssociatedFile (如有) 填入display_name欄位,該檔案的語言代碼須與建立時ImageClassifierOptions的display_names_locale欄位相符 (預設為「en」,即英文)。如果沒有任何可用的項目,系統只會填入結果的index欄位。
- ,以及 2 個或 4 個維度,也就是