Trình phát hiện đối tượng có thể xác định đối tượng nào trong một nhóm đối tượng đã biết có thể xuất hiện và cung cấp thông tin về vị trí của các đối tượng đó trong hình ảnh hoặc luồng video đã cho. Trình phát hiện đối tượng được huấn luyện để phát hiện sự hiện diện và vị trí của nhiều lớp đối tượng. Ví dụ: một mô hình có thể được huấn luyện bằng những hình ảnh chứa nhiều loại trái cây, cùng với một nhãn chỉ định loại trái cây mà hình ảnh đó đại diện (ví dụ: quả táo, quả chuối hoặc quả dâu tây) và dữ liệu chỉ định vị trí xuất hiện của từng đối tượng trong hình ảnh. Hãy xem ví dụ về tính năng phát hiện đối tượng để biết thêm thông tin về các bộ nhận diện đối tượng.
Sử dụng API Thư viện tác vụ ObjectDetector để triển khai các trình phát hiện đối tượng tuỳ chỉnh hoặc được huấn luyện trước vào ứng dụng di động của bạn.
Các tính năng chính của ObjectDetector API
Xử lý hình ảnh đầu vào, bao gồm xoay, đổi kích thước và chuyển đổi không gian màu.
Gắn nhãn ngôn ngữ trên bản đồ.
Ngưỡng điểm để lọc kết quả.
k kết quả phát hiện hàng đầu.
Danh sách cho phép và danh sách từ chối nhãn.
Các mô hình trình phát hiện đối tượng được hỗ trợ
Các mô hình sau đây chắc chắn sẽ tương thích với API ObjectDetector.
Các mô hình phát hiện đối tượng được huấn luyện trước trên TensorFlow Hub.
Các mô hình do AutoML Vision Edge Object Detection tạo.
Các mô hình do TensorFlow Lite Model Maker tạo cho trình phát hiện đối tượng.
Các mô hình tuỳ chỉnh đáp ứng yêu cầu về khả năng tương thích của mô hình.
Chạy suy luận bằng Java
Hãy xem Ứng dụng tham chiếu Phát hiện đối tượng để biết ví dụ về cách sử dụng ObjectDetector trong một ứng dụng Android.
Bước 1: Nhập phần phụ thuộc Gradle và các chế độ cài đặt khác
Sao chép tệp mô hình .tflite vào thư mục tài sản của mô-đun Android nơi mô hình sẽ chạy. Chỉ định rằng tệp không được nén và thêm thư viện TensorFlow Lite vào tệp build.gradle của mô-đun:
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'
}
Bước 2: Sử dụng mô hình
// 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);
Hãy xem mã nguồn và javadoc để biết thêm các lựa chọn định cấu hình ObjectDetector.
Chạy suy luận trong iOS
Bước 1: Cài đặt các phần phụ thuộc
Thư viện tác vụ hỗ trợ việc cài đặt bằng CocoaPods. Đảm bảo bạn đã cài đặt CocoaPods trên hệ thống. Vui lòng xem hướng dẫn cài đặt CocoaPods để biết hướng dẫn.
Vui lòng xem hướng dẫn về CocoaPods để biết thông tin chi tiết về cách thêm pod vào dự án Xcode.
Thêm nhóm TensorFlowLiteTaskVision vào Podfile.
target 'MyAppWithTaskAPI' do
use_frameworks!
pod 'TensorFlowLiteTaskVision'
end
Đảm bảo rằng mô hình .tflite mà bạn sẽ dùng để suy luận có trong gói ứng dụng của bạn.
Bước 2: Sử dụng mô hình
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];
Hãy xem mã nguồn để biết thêm các lựa chọn định cấu hình TFLObjectDetector.
Chạy suy luận trong Python
Bước 1: Cài đặt gói pip
pip install tflite-support
Bước 2: Sử dụng mô hình
# 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)
Hãy xem mã nguồn để biết thêm các lựa chọn định cấu hình ObjectDetector.
Chạy suy luận bằng 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();
Hãy xem mã nguồn để biết thêm các lựa chọn định cấu hình ObjectDetector.
Kết quả mẫu
Dưới đây là ví dụ về kết quả phát hiện của ssd mobilenet v1 từ TensorFlow Hub.

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
Kết xuất các hộp giới hạn lên hình ảnh đầu vào:

Hãy dùng thử công cụ minh hoạ CLI đơn giản cho ObjectDetector bằng mô hình và dữ liệu kiểm thử của riêng bạn.
Yêu cầu về khả năng tương thích của mô hình
API ObjectDetector yêu cầu một mô hình TFLite có Siêu dữ liệu mô hình TFLite bắt buộc. Xem ví dụ về cách tạo siêu dữ liệu cho các đối tượng phát hiện bằng TensorFlow Lite Metadata Writer API.
Các mô hình phát hiện đối tượng tương thích phải đáp ứng các yêu cầu sau:
Tensor hình ảnh đầu vào: (kTfLiteUInt8/kTfLiteFloat32)
- đầu vào hình ảnh có kích thước
[batch x height x width x channels]. - không hỗ trợ suy luận theo lô (
batchphải là 1). - chỉ hỗ trợ đầu vào RGB (
channelsphải là 3). - nếu loại là kTfLiteFloat32, bạn phải đính kèm NormalizationOptions vào siêu dữ liệu để chuẩn hoá dữ liệu đầu vào.
- đầu vào hình ảnh có kích thước
Các tensor đầu ra phải là 4 đầu ra của một thao tác
DetectionPostProcess, tức là:- Tensor vị trí (kTfLiteFloat32)
- tensor có kích thước
[1 x num_results x 4], mảng bên trong biểu thị các hộp giới hạn ở dạng [trên cùng, bên trái, bên phải, dưới cùng]. - Bạn phải đính kèm BoundingBoxProperties vào siêu dữ liệu và phải chỉ định
type=BOUNDARIESvà coordinate_type=RATIO. Tensor lớp (kTfLiteFloat32)
tensor có kích thước
[1 x num_results], mỗi giá trị đại diện cho chỉ mục số nguyên của một lớp.bạn có thể đính kèm (nhưng nên) (các) bản đồ nhãn dưới dạng AssociatedFile-s có loại TENSOR_VALUE_LABELS, chứa một nhãn trên mỗi dòng. Xem tệp nhãn mẫu. AssociatedFile đầu tiên như vậy (nếu có) được dùng để điền vào trường
class_namecủa kết quả. Trườngdisplay_nameđược điền từ AssociatedFile (nếu có) có ngôn ngữ khớp với trườngdisplay_names_localecủaObjectDetectorOptionsđược dùng tại thời điểm tạo ("en" theo mặc định, tức là tiếng Anh). Nếu không có kết quả nào trong số này, thì chỉ trườngindexcủa kết quả sẽ được điền.Tensor điểm số (kTfLiteFloat32)
tensor có kích thước
[1 x num_results], mỗi giá trị đại diện cho điểm số của đối tượng được phát hiện.Số lượng tensor phát hiện (kTfLiteFloat32)
số nguyên num_results dưới dạng một tensor có kích thước
[1].