整合物件偵測器

物件偵測器可以識別一組已知物件中可能存在的物件,並提供其在給定影像或視訊串流中位置的相關資訊。物件偵測器經過訓練,可以偵測多個類別物件的存在和位置。例如,模型可能會使用包含各種水果的影像進行訓練,並使用標籤指定水果的類別 (例如,蘋果、香蕉或草莓),以及指定每個物件在影像中顯示位置的資料。如需物件偵測器的詳細資訊,請參閱物件偵測簡介

使用 Task Library ObjectDetector API,將您的自訂物件偵測器或預先訓練的偵測器部署到您的行動應用程式中。

ObjectDetector API 的主要功能

  • 輸入影像處理,包括旋轉、調整大小和色彩空間轉換。

  • 標籤地圖地區設定。

  • 用於篩選結果的分數閾值。

  • 前 k 個偵測結果。

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

支援的物件偵測器模型

以下模型保證與 ObjectDetector API 相容。

在 Java 中執行推論

如需如何在 Android 應用程式中使用 ObjectDetector 的範例,請參閱 物件偵測參考應用程式

步驟 1:匯入 Gradle 依賴項和其他設定

.tflite 模型檔案複製到將執行模型的 Android 模組的 assets 目錄。指定不應壓縮檔案,並將 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 (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'
}

步驟 2:使用模型

// Initialization
ObjectDetectorOptions options =
    ObjectDetectorOptions.builder()
        .setBaseOptions(BaseOptions.builder().useGpu().build())
        .setMaxResults(1)
        .build();
ObjectDetector objectDetector =
    ObjectDetector.createFromFileAndOptions(
        context, modelFile, options);

// Run inference
List<Detection> results = objectDetector.detect(image);

如需設定 ObjectDetector 的更多選項,請參閱 原始碼和 javadoc

在 iOS 中執行推論

步驟 1:安裝依賴項

Task Library 支援使用 CocoaPods 安裝。請確認您的系統上已安裝 CocoaPods。如需操作說明,請參閱 CocoaPods 安裝指南

如需將 Pods 新增至 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: "ssd_mobilenet_v1",
                                            ofType: "tflite") else { return }

let options = ObjectDetectorOptions(modelPath: modelPath)

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

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

// Run inference
let detectionResult = try detector.detect(mlImage: mlImage)

Objective C

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

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

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

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

TFLObjectDetector *detector = [TFLObjectDetector objectDetectorWithOptions:options
                                                                     error:nil];

// Convert the input image to MLImage.
UIImage *image = [UIImage imageNamed:@"dogs.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
TFLDetectionResult *detectionResult = [detector detectWithGMLImage:gmlImage error:nil];

如需設定 TFLObjectDetector 的更多選項,請參閱 原始碼

在 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)
detection_options = processor.DetectionOptions(max_results=2)
options = vision.ObjectDetectorOptions(base_options=base_options, detection_options=detection_options)
detector = vision.ObjectDetector.create_from_options(options)

# Alternatively, you can create an object detector in the following manner:
# detector = vision.ObjectDetector.create_from_file(model_path)

# Run inference
image = vision.TensorImage.create_from_file(image_path)
detection_result = detector.detect(image)

如需設定 ObjectDetector 的更多選項,請參閱 原始碼

在 C++ 中執行推論

// Initialization
ObjectDetectorOptions options;
options.mutable_base_options()->mutable_model_file()->set_file_name(model_path);
std::unique_ptr<ObjectDetector> object_detector = ObjectDetector::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 DetectionResult result = object_detector->Detect(*frame_buffer).value();

如需設定 ObjectDetector 的更多選項,請參閱 原始碼

範例結果

以下是 TensorFlow Hub 中 ssd mobilenet v1 的偵測結果範例。

dogs

Results:
 Detection #0 (red):
  Box: (x: 355, y: 133, w: 190, h: 206)
  Top-1 class:
   index       : 17
   score       : 0.73828
   class name  : dog
 Detection #1 (green):
  Box: (x: 103, y: 15, w: 138, h: 369)
  Top-1 class:
   index       : 17
   score       : 0.73047
   class name  : dog

將邊界框渲染到輸入影像上

detection output

使用您自己的模型和測試資料試用適用於 ObjectDetector 的簡易 CLI 示範工具

模型相容性需求

ObjectDetector API 需要具有強制性 TFLite 模型元數據的 TFLite 模型。如需使用 TensorFlow Lite Metadata Writer API 建立物件偵測器元數據的範例,請參閱此處。

相容的物件偵測器模型應符合以下需求

  • 輸入影像張量:(kTfLiteUInt8/kTfLiteFloat32)

    • 大小為 [batch x height x width x channels] 的影像輸入。
    • 不支援批次推論 (需要 batch 為 1)。
    • 僅支援 RGB 輸入 (需要 channels 為 3)。
    • 如果類型為 kTfLiteFloat32,則需要將 NormalizationOptions 附加至元數據以進行輸入正規化。
  • 輸出張量必須是 DetectionPostProcess 運算的 4 個輸出,即

    • 位置張量 (kTfLiteFloat32)
      • 大小為 [1 x num_results x 4] 的張量,內部陣列以 [頂部、左側、右側、底部] 的形式表示邊界框。
      • 需要將 BoundingBoxProperties 附加至元數據,且必須指定 type=BOUNDARIES 和 `coordinate_type=RATIO。
    • 類別張量 (kTfLiteFloat32)

      • 大小為 [1 x num_results] 的張量,每個值代表類別的整數索引。
      • 選用 (但建議) 標籤地圖可以 AssociatedFile 的形式附加,類型為 TENSOR_VALUE_LABELS,每行包含一個標籤。請參閱 標籤檔案範例。第一個此類 AssociatedFile (如果有的話) 用於填入結果的 class_name 欄位。display_name 欄位會從 AssociatedFile (如果有的話) 填入,其地區設定符合建立時使用的 ObjectDetectorOptionsdisplay_names_locale 欄位 (預設為 "en",即英文)。如果這些都不可用,則只會填入結果的 index 欄位。
    • 分數張量 (kTfLiteFloat32)

      • 大小為 [1 x num_results] 的張量,每個值代表偵測到物件的分數。
    • 偵測數量張量 (kTfLiteFloat32)

      • 整數 num_results 作為大小為 [1] 的張量。