整合圖片嵌入器

圖片嵌入器可將圖片嵌入高維度的特徵向量 代表圖片的語意含義 特徵向量來評估圖片的語意相似度

相對於 圖片搜尋, 圖片嵌入器可即時計算圖片之間的相似度 而非搜尋從圖片語料庫建構的預先定義索引。

使用工作程式庫 ImageEmbedder API 部署自訂圖片嵌入器 整合到您的行動應用程式中

ImageEmbedder API 的主要功能

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

  • 輸入圖片的搜尋目標區域。

  • 這個內建公用程式函式可用於計算 餘弦相似度 特徵向量

支援的圖片嵌入器模型

下列型號保證與 ImageEmbedder 相容 也能使用 Google Cloud CLI 或 Compute Engine API

在 C++ 中執行推論

// Initialization
ImageEmbedderOptions options:
options.mutable_model_file_with_metadata()->set_file_name(model_path);
options.set_l2_normalize(true);
std::unique_ptr<ImageEmbedder> image_embedder = ImageEmbedder::CreateFromOptions(options).value();

// Create input frame_buffer_1 and frame_buffer_2 from your inputs `image_data1`, `image_data2`, `image_dimension1` and `image_dimension2`.
// See more information here: tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h
std::unique_ptr<FrameBuffer> frame_buffer_1 = CreateFromRgbRawBuffer(
      image_data1, image_dimension1);
std::unique_ptr<FrameBuffer> frame_buffer_2 = CreateFromRgbRawBuffer(
      image_data2, image_dimension2);

// Run inference on two images.
const EmbeddingResult result_1 = image_embedder->Embed(*frame_buffer_1);
const EmbeddingResult result_2 = image_embedder->Embed(*frame_buffer_2);

// Compute cosine similarity.
double similarity = ImageEmbedder::CosineSimilarity(
    result_1.embeddings[0].feature_vector(),
    result_2.embeddings[0].feature_vector());

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

在 Python 中執行推論

步驟 1:安裝 TensorFlow Lite Support Pypi 套件。

您可以使用下列指令安裝 TensorFlow Lite Support Pypi 套件 指令:

pip install tflite-support

步驟 2:使用模型

from tflite_support.task import vision

# Initialization.
image_embedder = vision.ImageEmbedder.create_from_file(model_path)

# Run inference on two images.
image_1 = vision.TensorImage.create_from_file('/path/to/image1.jpg')
result_1 = image_embedder.embed(image_1)
image_2 = vision.TensorImage.create_from_file('/path/to/image2.jpg')
result_2 = image_embedder.embed(image_2)

# Compute cosine similarity.
feature_vector_1 = result_1.embeddings[0].feature_vector
feature_vector_2 = result_2.embeddings[0].feature_vector
similarity = image_embedder.cosine_similarity(
    result_1.embeddings[0].feature_vector, result_2.embeddings[0].feature_vector)

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

搜尋結果範例

正規化特徵向量之間的餘弦相似度會傳回介於 -1 之間的分數 和 1.越高越好;也就是說,餘弦相似度為 1 表示兩個向量 完全相同。

Cosine similarity: 0.954312

試試簡易設計 ImageEmbedder 適用的 CLI 示範工具 使用自己的模型與測試資料

模型相容性需求

ImageEmbedder API 預期的 TFLite 模型可選用,但很強 建議 TFLite 模型中繼資料

相容的圖片嵌入器模型應符合下列規定:

  • 輸入圖片張量 (kTfLiteUInt8/kTfLiteFloat32)

    • 輸入大小為 [batch x height x width x channels] 的圖片。
    • 不支援批次推論 (batch 須為 1)。
    • 僅支援 RGB 輸入 (channels 必須為 3)。
    • 如果型別是 kTfLiteFloat32,就必須使用正規化選項 附加於中繼資料,以便進行輸入正規化
  • 至少一個輸出張量 (kTfLiteUInt8/kTfLiteFloat32)

    • 其中 N 元件與傳回的 N 維度對應 第一個輸出層的特徵向量
    • 2 或 4 個維度,例如 [1 x N][1 x 1 x 1 x N]