整合物件偵測工具

物件偵測器可以識別已知物件組中可能存在的物件,並提供這些物件在指定圖片或影片串流中的位置資訊。物件偵測工具經過訓練後,可偵測多個類別的物件是否存在,以及物件的位置。舉例來說,模型可能會使用含有各種水果的圖片進行訓練,並搭配指定水果類別的標籤 (例如蘋果、香蕉或草莓),以及指定每個物件在圖片中顯示位置的資料。如要進一步瞭解物件偵測器,請參閱物件偵測範例

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

ObjectDetector API 的主要功能

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

  • 標記地圖語言區域。

  • 篩選結果的分數門檻。

  • 前 k 個偵測結果。

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

支援的物件偵測模型

下列機型保證與 ObjectDetector API 相容。

在 Java 中執行推論作業

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

步驟 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
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:安裝依附元件

工作程式庫支援使用 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: "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 的偵測結果範例。

狗

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

將定界框轉譯至輸入圖片:

偵測輸出

使用自己的模型和測試資料,試用 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] 的張量,內部陣列代表邊界方塊,格式為 [上、左、右、下]。
    • 定界框屬性必須附加至中繼資料,且必須指定 type=BOUNDARIES 和 `coordinate_type=RATIO。
    • 類別張量 (kTfLiteFloat32)

    • 大小為 [1 x num_results] 的張量,每個值代表類別的整數索引。

    • (建議) 標籤對應可附加為類型為 TENSOR_VALUE_LABELS 的 AssociatedFile,每行包含一個標籤。請參閱標籤檔案範例。系統會使用第一個這類 AssociatedFile (如有) 填入結果的 class_name 欄位。系統會從 AssociatedFile (如有) 填入 display_name 欄位,該檔案的語言代碼須與建立時 ObjectDetectorOptions 欄位的 display_names_locale 相符 (預設為「en」,即英文)。如果沒有任何可用的資訊,則只會填入結果的 index 欄位。

    • 分數張量 (kTfLiteFloat32)

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

    • 偵測張量數量 (kTfLiteFloat32)

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