整合物件偵測工具

物件偵測工具可以辨識一組已知物件可能存在 並提供位置相關資訊,指出這些內容在特定圖片或影片中的位置 串流。物件偵測工具經過訓練,可偵測裝置內部的 多個物件的類別例如,模型能以圖片訓練 ,以及一個標籤,當中指出 所代表的水果類別 (例如蘋果、香蕉或草莓)。 指定每個物件在圖片中位置的資料。詳情請參閱 物件偵測範例 ,進一步瞭解物件偵測工具。

使用工作程式庫 ObjectDetector API 部署自訂物件偵測工具 或是在行動應用程式中預先訓練

ObjectDetector API 的主要功能

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

  • 標籤對應語言代碼。

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

  • 「前 K 個」的偵測結果。

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

支援的物件偵測工具模型

下列型號保證與 ObjectDetector 相容 也能使用 Google Cloud CLI 或 Compute Engine 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);

詳情請參閱 原始碼和 javadoc 取得更多設定 ObjectDetector 的選項。

在 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: "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 的選項。

搜尋結果範例

以下舉例說明 ssd mobilenet v1 載入預先訓練的 BERT 模型

狗

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,就必須使用正規化選項 附加於中繼資料,以便進行輸入正規化
  • 輸出張量必須是 DetectionPostProcess 運算的 4 個輸出內容,即

    • 位置張量 (kTfLiteFloat32)
      • 大小為 [1 x num_results x 4] 的張量,代表的內部陣列 的定界框 [top、left、right、Bottom] 格式。
      • 必須將 BoundingBoxProperties 附加至中繼資料 且必須指定 type=BOUNDARIES 和 `Coordinate_type=RATIO。
    • 類別張量 (kTfLiteFloat32)

      • 大小為 [1 x num_results] 的張量,每個值代表 類別整數索引。
      • (但建議使用) 標籤對應,可以將 關聯檔案 (類型:TENSOR_VALUE_LABELS) 包含一個標籤 。詳情請參閱 標籤檔案範例。 第一個這類 AssociatedFile (如有) 會用來填入 結果的 class_name 欄位。display_name 欄位是 從關聯檔案 (如有) 中填入語言代碼符合 使用的 ObjectDetectorOptionsdisplay_names_locale 欄位 建立時間 (預設為「en」,例如英文)。如果這些都不是 可用,只有結果的 index 欄位會填入內容。
    • 分數張量 (kTfLiteFloat32)

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

      • 整數 num_results 以大小 [1] 的張量表示。