Transformers 文件

OWL-ViT

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

OWL-ViT

PyTorch

概述

OWL-ViT (Vision Transformer for Open-World Localization的縮寫) 是在 Simple Open-Vocabulary Object Detection with Vision Transformers 一文中由 Matthias Minderer、Alexey Gritsenko、Austin Stone、Maxim Neumann、Dirk Weissenborn、Alexey Dosovitskiy、Aravindh Mahendran、Anurag Arnab、Mostafa Dehghani、Zhuoran Shen、Xiao Wang、Xiaohua Zhai、Thomas Kipf 和 Neil Houlsby 提出的。OWL-ViT 是一個在多種(影像,文字)對上訓練的開放詞彙目標檢測網路。它可以用來透過一個或多個文字查詢來查詢影像,以搜尋和檢測文字中描述的目標物件。

論文摘要如下:

將簡單的架構與大規模預訓練相結合,已在影像分類方面取得了巨大進步。對於目標檢測,預訓練和縮放方法尚未成熟,尤其是在長尾和開放詞彙的場景下,訓練資料相對稀缺。在本文中,我們提出了一種將影像-文字模型遷移到開放詞彙目標檢測的有效方法。我們使用標準的 Vision Transformer 架構,並進行了最小的修改,採用對比影像-文字預訓練和端到端檢測微調。我們對這種設定的縮放屬性的分析表明,增加影像級預訓練和模型大小,能夠在下游檢測任務上帶來持續的改進。我們提供了實現零樣本文字條件和單樣本影像條件目標檢測非常強大效能所需的適應策略和正則化方法。程式碼和模型可在 GitHub 上獲取。

drawing OWL-ViT 架構。摘自原始論文

此模型由 adirik 貢獻。原始程式碼可在此處找到。

使用技巧

OWL-ViT 是一種零樣本文字條件的目標檢測模型。OWL-ViT 使用 CLIP 作為其多模態骨幹網路,使用類似 ViT 的 Transformer 獲取視覺特徵,並使用因果語言模型獲取文字特徵。為了將 CLIP 用於檢測,OWL-ViT 移除了視覺模型的最終 token 池化層,並在每個 transformer 輸出 token 上附加了一個輕量級的分類和邊界框頭。透過將固定的分類層權重替換為從文字模型中獲取的類名嵌入,實現了開放詞彙分類。作者首先從頭訓練 CLIP,然後使用分類和邊界框頭在標準檢測資料集上進行端到端微調,使用二分匹配損失。每張影像可以使用一個或多個文字查詢來執行零樣本文字條件的目標檢測。

OwlViTImageProcessor 可用於為模型調整影像大小(或縮放)和歸一化,而 CLIPTokenizer 用於編碼文字。OwlViTProcessorOwlViTImageProcessorCLIPTokenizer 包裝成單個例項,以同時編碼文字和準備影像。以下示例展示瞭如何使用 OwlViTProcessorOwlViTForObjectDetection 進行目標檢測。

>>> import requests
>>> from PIL import Image
>>> import torch

>>> from transformers import OwlViTProcessor, OwlViTForObjectDetection

>>> processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32")
>>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text_labels = [["a photo of a cat", "a photo of a dog"]]
>>> inputs = processor(text=text_labels, images=image, return_tensors="pt")
>>> outputs = model(**inputs)

>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.tensor([(image.height, image.width)])
>>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> results = processor.post_process_grounded_object_detection(
...     outputs=outputs, target_sizes=target_sizes, threshold=0.1, text_labels=text_labels
... )
>>> # Retrieve predictions for the first image for the corresponding text queries
>>> result = results[0]
>>> boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
>>> for box, score, text_label in zip(boxes, scores, text_labels):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29]
Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]

資源

關於使用 OWL-ViT 進行零樣本和單樣本(影像引導)目標檢測的演示筆記本可以在這裡找到。

OwlViTConfig

class transformers.OwlViTConfig

< >

( text_config = None vision_config = None projection_dim = 512 logit_scale_init_value = 2.6592 return_dict = True **kwargs )

引數

  • text_config (dict, 可選) — 用於初始化 OwlViTTextConfig 的配置選項字典。
  • vision_config (dict, 可選) — 用於初始化 OwlViTVisionConfig 的配置選項字典。
  • projection_dim (int, 可選, 預設為 512) — 文字和視覺投影層的維度。
  • logit_scale_init_value (float, 可選, 預設為 2.6592) — logit_scale 引數的初始值。預設值根據原始 OWL-ViT 實現使用。
  • return_dict (bool, 可選, 預設為 True) — 模型是否應返回一個字典。如果為 False,則返回一個元組。
  • kwargs (可選) — 關鍵字引數字典。

OwlViTConfig 是用於儲存 OwlViTModel 配置的配置類。它用於根據指定的引數例項化一個 OWL-ViT 模型,定義文字模型和視覺模型配置。使用預設值例項化配置將產生與 OWL-ViT google/owlvit-base-patch32 架構相似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。

from_text_vision_configs

< >

( text_config: dict vision_config: dict **kwargs ) OwlViTConfig

返回

OwlViTConfig

一個配置物件的例項

從 owlvit 文字模型配置和 owlvit 視覺模型配置例項化一個 OwlViTConfig(或其派生類)。

OwlViTTextConfig

class transformers.OwlViTTextConfig

< >

( vocab_size = 49408 hidden_size = 512 intermediate_size = 2048 num_hidden_layers = 12 num_attention_heads = 8 max_position_embeddings = 16 hidden_act = 'quick_gelu' layer_norm_eps = 1e-05 attention_dropout = 0.0 initializer_range = 0.02 initializer_factor = 1.0 pad_token_id = 0 bos_token_id = 49406 eos_token_id = 49407 **kwargs )

引數

  • vocab_size (int, 可選, 預設為 49408) — OWL-ViT 文字模型的詞彙表大小。定義了在呼叫 OwlViTTextModel 時傳入的 inputs_ids 可以表示的不同詞元的數量。
  • hidden_size (int, 可選, 預設為 512) — 編碼器層和池化層的維度。
  • intermediate_size (int, 可選, 預設為 2048) — Transformer 編碼器中“中間”(即前饋)層的維度。
  • num_hidden_layers (int, 可選, 預設為 12) — Transformer 編碼器中的隱藏層數量。
  • num_attention_heads (int, 可選, 預設為 8) — Transformer 編碼器中每個注意力層的注意力頭數量。
  • max_position_embeddings (int, 可選, 預設為 16) — 該模型可能使用的最大序列長度。通常將其設定為一個較大的值以備不時之需(例如,512、1024 或 2048)。
  • hidden_act (strfunction, 可選, 預設為 "quick_gelu") — 編碼器和池化器中的非線性啟用函式(函式或字串)。如果為字串,支援 "gelu""relu""selu""gelu_new""quick_gelu"
  • layer_norm_eps (float, 可選, 預設為 1e-05) — 層歸一化層使用的 epsilon 值。
  • attention_dropout (float, 可選, 預設為 0.0) — 注意力機率的 dropout 比率。
  • initializer_range (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的 truncated_normal_initializer 的標準差。
  • initializer_factor (float, 可選, 預設為 1.0) — 初始化所有權重矩陣的因子(應保持為 1,內部用於初始化測試)。
  • pad_token_id (int, 可選, 預設為 0) — 輸入序列中填充詞元的 ID。
  • bos_token_id (int, 可選, 預設為 49406) — 輸入序列中序列開始詞元的 ID。
  • eos_token_id (int, 可選, 預設為 49407) — 輸入序列中序列結束詞元的 ID。

這是用於儲存 OwlViTTextModel 配置的配置類。它用於根據指定的引數例項化一個 OwlViT 文字編碼器,定義模型架構。使用預設值例項化配置將產生與 OwlViT google/owlvit-base-patch32 架構相似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。

示例

>>> from transformers import OwlViTTextConfig, OwlViTTextModel

>>> # Initializing a OwlViTTextModel with google/owlvit-base-patch32 style configuration
>>> configuration = OwlViTTextConfig()

>>> # Initializing a OwlViTTextConfig from the google/owlvit-base-patch32 style configuration
>>> model = OwlViTTextModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

OwlViTVisionConfig

class transformers.OwlViTVisionConfig

< >

( hidden_size = 768 intermediate_size = 3072 num_hidden_layers = 12 num_attention_heads = 12 num_channels = 3 image_size = 768 patch_size = 32 hidden_act = 'quick_gelu' layer_norm_eps = 1e-05 attention_dropout = 0.0 initializer_range = 0.02 initializer_factor = 1.0 **kwargs )

引數

  • hidden_size (int, 可選, 預設為 768) — 編碼器層和池化層的維度。
  • intermediate_size (int, 可選, 預設為 3072) — Transformer 編碼器中“中間”(即前饋)層的維度。
  • num_hidden_layers (int, 可選, 預設為 12) — Transformer 編碼器中的隱藏層數量。
  • num_attention_heads (int, 可選, 預設為 12) — Transformer 編碼器中每個注意力層的注意力頭數量。
  • num_channels (int, 可選, 預設為 3) — 輸入影像中的通道數。
  • image_size (int, 可選, 預設為 768) — 每張影像的大小(解析度)。
  • patch_size (int, 可選, 預設為 32) — 每個影像塊的大小(解析度)。
  • hidden_act (strfunction, 可選, 預設為 "quick_gelu") — 編碼器和池化器中的非線性啟用函式(函式或字串)。如果為字串,支援 "gelu""relu""selu""gelu_new""quick_gelu"
  • layer_norm_eps (float, optional, defaults to 1e-05) — 層歸一化層使用的 epsilon 值。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力機率的 dropout 比率。
  • initializer_range (float, optional, defaults to 0.02) — 用於初始化所有權重矩陣的 truncated_normal_initializer 的標準差。
  • initializer_factor (float, optional, defaults to 1.0) — 用於初始化所有權重矩陣的因子(應保持為 1,內部用於初始化測試)。

這是一個配置類,用於儲存 OwlViTVisionModel 的配置。它用於根據指定的引數例項化一個 OWL-ViT 影像編碼器,定義模型架構。使用預設值例項化配置將產生與 OWL-ViT google/owlvit-base-patch32 架構類似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。

示例

>>> from transformers import OwlViTVisionConfig, OwlViTVisionModel

>>> # Initializing a OwlViTVisionModel with google/owlvit-base-patch32 style configuration
>>> configuration = OwlViTVisionConfig()

>>> # Initializing a OwlViTVisionModel model from the google/owlvit-base-patch32 style configuration
>>> model = OwlViTVisionModel(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

OwlViTImageProcessor

class transformers.OwlViTImageProcessor

< >

( do_resize = True size = None resample = <Resampling.BICUBIC: 3> do_center_crop = False crop_size = None do_rescale = True rescale_factor = 0.00392156862745098 do_normalize = True image_mean = None image_std = None **kwargs )

引數

  • do_resize (bool, optional, defaults to True) — 是否將輸入影像的短邊調整到特定的 size
  • size (dict[str, int], optional, defaults to {“height” — 768, “width”: 768}):用於調整影像大小的尺寸。僅在 do_resize 設定為 True 時有效。如果 size 是一個序列,如 (h, w),輸出尺寸將與之匹配。如果 size 是一個整數,則影像將被調整為 (size, size)。
  • resample (int, optional, defaults to Resampling.BICUBIC) — 可選的重取樣過濾器。可以是 PIL.Image.Resampling.NEARESTPIL.Image.Resampling.BOXPIL.Image.Resampling.BILINEARPIL.Image.Resampling.HAMMINGPIL.Image.Resampling.BICUBICPIL.Image.Resampling.LANCZOS 之一。僅在 do_resize 設定為 True 時有效。
  • do_center_crop (bool, optional, defaults to False) — 是否在中心裁剪輸入。如果輸入尺寸的任何一邊小於 crop_size,影像將被填充 0,然後進行中心裁剪。
  • crop_size (int, optional, defaults to {“height” — 768, “width”: 768}):用於中心裁剪影像的尺寸。僅在 do_center_crop 設定為 True 時有效。
  • do_rescale (bool, optional, defaults to True) — 是否透過特定因子對輸入進行縮放。
  • rescale_factor (float, optional, defaults to 1/255) — 用於縮放影像的因子。僅在 do_rescale 設定為 True 時有效。
  • do_normalize (bool, optional, defaults to True) — 是否使用 image_meanimage_std 對輸入進行歸一化。應用中心裁剪時所需的輸出尺寸。僅在 do_center_crop 設定為 True 時有效。
  • image_mean (list[int], optional, defaults to [0.48145466, 0.4578275, 0.40821073]) — 用於歸一化影像時每個通道的均值序列。
  • image_std (list[int], optional, defaults to [0.26862954, 0.26130258, 0.27577711]) — 用於歸一化影像時每個通道的標準差序列。

構建一個 OWL-ViT 影像處理器。

此影像處理器繼承自 ImageProcessingMixin,其中包含大多數主要方法。使用者應參考此超類以獲取有關這些方法的更多資訊。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[transformers.utils.generic.TensorType, str, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

引數

  • images (ImageInput) — 待準備的影像或影像批次。期望單個或批次影像的畫素值範圍為 0 到 255。如果傳入畫素值在 0 到 1 之間的影像,請設定 do_rescale=False
  • do_resize (bool, optional, defaults to self.do_resize) — 是否調整輸入大小。如果為 True,將輸入調整為 size 指定的大小。
  • size (dict[str, int], optional, defaults to self.size) — 輸入要調整到的大小。僅在 do_resize 設定為 True 時有效。
  • resample (PILImageResampling, optional, defaults to self.resample) — 調整輸入大小時使用的重取樣過濾器。僅在 do_resize 設定為 True 時有效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否對輸入進行中心裁剪。如果為 True,將輸入中心裁剪為 crop_size 指定的大小。
  • crop_size (dict[str, int], optional, defaults to self.crop_size) — 輸入要中心裁剪到的大小。僅在 do_center_crop 設定為 True 時有效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否縮放輸入。如果為 True,將輸入除以 rescale_factor 進行縮放。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 縮放輸入的因子。僅在 do_rescale 設定為 True 時有效。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否歸一化輸入。如果為 True,將透過減去 image_mean 併除以 image_std 來歸一化輸入。
  • image_mean (Union[float, list[float]], optional, defaults to self.image_mean) — 歸一化時從輸入中減去的均值。僅在 do_normalize 設定為 True 時有效。
  • image_std (Union[float, list[float]], optional, defaults to self.image_std) — 歸一化時用於除以輸入的標準差。僅在 do_normalize 設定為 True 時有效。
  • return_tensors (str or TensorType, optional) — 返回的張量型別。可以是以下之一:
    • 未設定:返回 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回 tf.Tensor 型別的批次。
    • TensorType.PYTORCH'pt':返回 torch.Tensor 型別的批次。
    • TensorType.NUMPY'np':返回 np.ndarray 型別的批次。
    • TensorType.JAX'jax':返回 jax.numpy.ndarray 型別的批次。
  • data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) — 輸出影像的通道維度格式。可以是以下之一:
    • ChannelDimension.FIRST:影像格式為 (通道數, 高度, 寬度)。
    • ChannelDimension.LAST:影像格式為 (高度, 寬度, 通道數)。
    • 未設定:預設為輸入影像的通道維度格式。
  • input_data_format (ChannelDimension or str, optional) — 輸入影像的通道維度格式。如果未設定,將從輸入影像中推斷通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (通道數, 高度, 寬度)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (高度, 寬度, 通道數)。
    • "none"ChannelDimension.NONE:影像格式為 (高度, 寬度)。

為模型準備影像或影像批次。

OwlViTImageProcessorFast

class transformers.OwlViTImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )

構建一個快速的 Owlvit 影像處理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

引數

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]) — 待預處理的影像。期望單個或批次影像的畫素值範圍為 0 到 255。如果傳入畫素值在 0 到 1 之間的影像,請設定 do_rescale=False
  • do_resize (bool, optional) — 是否調整影像大小。
  • size (dict[str, int], optional) — 描述模型的最大輸入尺寸。
  • default_to_square (bool, optional) — 如果 size 是整數,是否在調整大小時預設為正方形影像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果調整影像大小,使用的重取樣過濾器。這可以是 PILImageResampling 列舉之一。僅在 do_resize 設定為 True 時有效。
  • do_center_crop (bool, optional) — 是否對影像進行中心裁剪。
  • crop_size (dict[str, int], optional) — 應用 center_crop 後的輸出影像尺寸。
  • do_rescale (bool, optional) — 是否縮放影像。
  • rescale_factor (Union[int, float, NoneType]) — 如果設定 do_rescaleTrue,用於縮放影像的縮放因子。
  • do_normalize (bool, optional) — 是否歸一化影像。
  • image_mean (Union[float, list[float], NoneType]) — 用於歸一化的影像均值。僅在 do_normalize 設定為 True 時有效。
  • image_std (Union[float, list[float], NoneType]) — 用於歸一化的影像標準差。僅在 do_normalize 設定為 True 時有效。
  • do_convert_rgb (bool, optional) — 是否將影像轉換為 RGB。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果設定為 `pt`,返回堆疊的張量,否則返回張量列表。
  • data_format (~image_utils.ChannelDimension, optional) — 僅支援 ChannelDimension.FIRST。為與慢速處理器相容而新增。
  • input_data_format (Union[str, ~image_utils.ChannelDimension, NoneType]) — 輸入影像的通道維度格式。如果未設定,則從輸入影像中推斷通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:影像格式為 (height, width)。
  • device (torch.device, optional) — 用於處理影像的裝置。如果未設定,則從輸入影像中推斷裝置。
  • disable_grouping (bool, optional) — 是否停用按尺寸對影像進行分組,以便單獨處理而不是批次處理。如果為 None,則在影像位於 CPU 上時設定為 True,否則設定為 False。此選擇基於經驗觀察,詳見此處:https://github.com/huggingface/transformers/pull/38157

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/陣列/張量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可選) — 您可以在此處提供一個`tensor_type`,以便在初始化時將整數列表轉換為PyTorch/TensorFlow/Numpy張量。

post_process_object_detection

< >

( outputs: OwlViTObjectDetectionOutput threshold: float = 0.1 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None ) list[Dict]

引數

  • outputs (OwlViTObjectDetectionOutput) — 模型的原始輸出。
  • threshold (float, optional, defaults to 0.1) — 用於保留目標檢測預測的分數閾值。
  • target_sizes (torch.Tensor or list[tuple[int, int]], optional) — 形狀為 (batch_size, 2) 的張量或包含批次中每個影像目標尺寸 (height, width) 的元組列表 (tuple[int, int])。如果未設定,則不會調整預測尺寸。

返回

list[Dict]

一個字典列表,每個字典包含以下鍵:

  • “scores”:影像上每個預測框的置信度分數。
  • “labels”:模型在影像上預測的類別索引。
  • “boxes”:影像邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。

OwlViTForObjectDetection 的原始輸出轉換為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最終邊界框。

post_process_image_guided_detection

< >

( outputs threshold = 0.0 nms_threshold = 0.3 target_sizes = None ) list[Dict]

引數

  • outputs (OwlViTImageGuidedObjectDetectionOutput) — 模型的原始輸出。
  • threshold (float, optional, defaults to 0.0) — 用於過濾預測框的最低置信度閾值。
  • nms_threshold (float, optional, defaults to 0.3) — 用於對重疊框進行非極大值抑制的 IoU 閾值。
  • target_sizes (torch.Tensor, optional) — 形狀為 (batch_size, 2) 的張量,其中每個條目是批處理中相應影像的 (height, width)。如果設定,則預測的歸一化邊界框將重新縮放到目標尺寸。如果留空,則預測不會被非歸一化。

返回

list[Dict]

一個字典列表,每個字典包含模型預測的批次中一個影像的分數、標籤和框。所有標籤都設定為 None,因為 OwlViTForObjectDetection.image_guided_detection 執行一次性目標檢測。

OwlViTForObjectDetection.image_guided_detection() 的輸出轉換為 COCO API 期望的格式。

OwlViTProcessor

class transformers.OwlViTProcessor

< >

( image_processor = None tokenizer = None **kwargs )

引數

  • image_processor (OwlViTImageProcessor, optional) — 影像處理器是必需的輸入。
  • tokenizer ([CLIPTokenizer, CLIPTokenizerFast], optional) — 分詞器是必需的輸入。

構建一個 OWL-ViT 處理器,將 OwlViTImageProcessorCLIPTokenizer/CLIPTokenizerFast 包裝成一個單一的處理器,該處理器繼承了影像處理器和分詞器的功能。有關更多資訊,請參閱 call()decode()

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None text: typing.Union[str, list[str], list[list[str]]] = None *args audio = None videos = None **kwargs: typing_extensions.Unpack[transformers.models.owlvit.processing_owlvit.OwlViTProcessorKwargs] ) BatchFeature

引數

  • images (PIL.Image.Image, np.ndarray, torch.Tensor, list[PIL.Image.Image], list[np.ndarray], —
  • list[torch.Tensor]) — 要準備的影像或影像批次。每個影像可以是 PIL 影像、NumPy 陣列或 PyTorch 張量。支援 channels-first 和 channels-last 格式。
  • text (str, list[str], list[list[str]]) — 要編碼的序列或序列批次。每個序列可以是一個字串或一個字串列表(預分詞的字串)。如果序列以字串列表(預分詞)的形式提供,則必須設定 is_split_into_words=True(以消除與序列批次的歧義)。
  • query_images (PIL.Image.Image, np.ndarray, torch.Tensor, list[PIL.Image.Image], list[np.ndarray], list[torch.Tensor]) — 要準備的查詢影像,每個目標影像需要一個查詢影像。每個影像可以是 PIL 影像、NumPy 陣列或 PyTorch 張量。對於 NumPy 陣列/PyTorch 張量,每個影像的形狀應為 (C, H, W),其中 C 是通道數,H 和 W 是影像的高度和寬度。
  • return_tensors (str or TensorType, optional) — 如果設定,將返回特定框架的張量。可接受的值為:
    • 'tf':返回 TensorFlow tf.constant 物件。
    • 'pt':返回 PyTorch torch.Tensor 物件。
    • 'np':返回 NumPy np.ndarray 物件。
    • 'jax':返回 JAX jnp.ndarray 物件。

返回

批次特徵

一個具有以下欄位的 BatchFeature

  • input_ids — 要輸入到模型的 token ID 列表。當 text 不為 None 時返回。
  • attention_mask — 指定模型應關注哪些標記的索引列表(當 return_attention_mask=True“attention_mask”self.model_input_names 中且 text 不為 None 時)。
  • pixel_values — 要輸入到模型的畫素值。當 images 不為 None 時返回。
  • query_pixel_values — 要輸入到模型中的查詢影像的畫素值。當 query_images 不為 None 時返回。

為模型準備一個或多個文字和影像的主要方法。此方法將 textkwargs 引數轉發到 CLIPTokenizerFast 的 call()(如果 text 不為 None)以編碼文字。為了準備影像,此方法將 imageskwrags 引數轉發到 CLIPImageProcessor 的 call()(如果 images 不為 None)。請參閱上述兩個方法的文件字串以獲取更多資訊。

post_process_grounded_object_detection

< >

( outputs: OwlViTObjectDetectionOutput threshold: float = 0.1 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None text_labels: typing.Optional[list[list[str]]] = None ) list[Dict]

引數

  • outputs (OwlViTObjectDetectionOutput) — 模型的原始輸出。
  • threshold (float, optional, defaults to 0.1) — 用於保留目標檢測預測的分數閾值。
  • target_sizes (torch.Tensor or list[tuple[int, int]], optional) — 形狀為 (batch_size, 2) 的張量或包含批次中每個影像目標尺寸 (height, width) 的元組列表 (tuple[int, int])。如果未設定,則不會調整預測尺寸。
  • text_labels (list[list[str]], optional) — 批次中每個影像的文字標籤列表的列表。如果未設定,則輸出中的“text_labels”將設定為 None

返回

list[Dict]

一個字典列表,每個字典包含以下鍵:

  • “scores”:影像上每個預測框的置信度分數。
  • “labels”:模型在影像上預測的類別索引。
  • “boxes”:影像邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
  • “text_labels”:影像上每個預測邊界框的文字標籤。

OwlViTForObjectDetection 的原始輸出轉換為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最終邊界框。

post_process_image_guided_detection

< >

( outputs: OwlViTImageGuidedObjectDetectionOutput threshold: float = 0.0 nms_threshold: float = 0.3 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None ) list[Dict]

引數

  • outputs (OwlViTImageGuidedObjectDetectionOutput) — 模型的原始輸出。
  • threshold (float, optional, defaults to 0.0) — 用於過濾預測框的最低置信度閾值。
  • nms_threshold (float, optional, defaults to 0.3) — 用於對重疊框進行非極大值抑制的 IoU 閾值。
  • target_sizes (torch.Tensor, optional) — 形狀為 (batch_size, 2) 的張量,其中每個條目是批處理中相應影像的 (height, width)。如果設定,則預測的歸一化邊界框將重新縮放到目標尺寸。如果留空,則預測不會被非歸一化。

返回

list[Dict]

一個字典列表,每個字典包含以下鍵:

  • “scores”:影像上每個預測框的置信度分數。
  • “boxes”:影像邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
  • “labels”:設定為 None

OwlViTForObjectDetection.image_guided_detection() 的輸出轉換為 COCO API 期望的格式。

OwlViTModel

class transformers.OwlViTModel

< >

( config: OwlViTConfig )

引數

  • config (OwlViTConfig) — 包含模型所有引數的模型配置類。用配置檔案初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。

裸 Owlvit 模型,輸出原始隱藏狀態,頂部沒有任何特定的頭。

此模型繼承自 PreTrainedModel。請檢視超類文件,瞭解庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

該模型也是 PyTorch torch.nn.Module 的子類。可以像常規 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與通用用法和行為相關的事項。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = None pixel_values: typing.Optional[torch.FloatTensor] = None attention_mask: typing.Optional[torch.Tensor] = None return_loss: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: bool = False return_base_image_embeds: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.owlvit.modeling_owlvit.OwlViTOutput or tuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor of shape (batch_size, sequence_length), optional) — 詞彙表中輸入序列標記的索引。預設情況下將忽略填充。

    可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什麼是輸入 ID?

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, image_size, image_size), optional) — 與輸入影像相對應的張量。可以使用 {image_processor_class} 獲取畫素值。有關詳細資訊,請參閱 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 處理影像)。
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — 掩碼,以避免對填充標記索引執行注意力。掩碼值選自 [0, 1]

    • 1 表示未被遮蔽的標記,
    • 0 表示被遮蔽的標記。

    什麼是注意力掩碼?

  • return_loss (bool, optional) — 是否返回對比損失。
  • output_attentions (bool, optional) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • interpolate_pos_encoding (bool, defaults to False) — 是否對預訓練的位置編碼進行插值。
  • return_base_image_embeds (bool, optional) — 是否返回基礎影像嵌入。
  • return_dict (bool, optional) — 是返回一個 ModelOutput 而不是一個普通的元組。

返回

transformers.models.owlvit.modeling_owlvit.OwlViTOutput or tuple(torch.FloatTensor)

一個 transformers.models.owlvit.modeling_owlvit.OwlViTOutput 或一個 torch.FloatTensor 的元組(如果傳遞了 return_dict=False 或當 config.return_dict=False),包含根據配置 (OwlViTConfig) 和輸入的不同元素。

  • loss (torch.FloatTensor,形狀為 (1,), 可選, 當 return_lossTrue 時返回) — 影像-文字相似度的對比損失。
  • logits_per_image (torch.FloatTensor of shape (image_batch_size, text_batch_size)) — image_embedstext_embeds 之間的縮放點積得分。這表示圖文相似性得分。
  • logits_per_text (torch.FloatTensor of shape (text_batch_size, image_batch_size)) — text_embedsimage_embeds 之間的縮放點積得分。這表示文圖相似性得分。
  • text_embeds (torch.FloatTensor of shape (batch_size * num_max_text_queries, output_dim) — 透過將投影層應用於 OwlViTTextModel 的池化輸出而獲得的文字嵌入。
  • image_embeds (torch.FloatTensor of shape (batch_size, output_dim) — 透過將投影層應用於 OwlViTVisionModel 的池化輸出而獲得的影像嵌入。
  • text_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output, defaults to None) — OwlViTTextModel 的輸出。
  • vision_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output, defaults to None) — OwlViTVisionModel 的輸出。

OwlViTModel 的 forward 方法,覆蓋了 __call__ 特殊方法。

雖然前向傳播的流程需要在此函式內定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理預處理和後處理步驟,而後者會靜默地忽略它們。

示例

>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(text=[["a photo of a cat", "a photo of a dog"]], images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
>>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities

get_text_features

< >

( input_ids: typing.Optional[torch.Tensor] = None attention_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) text_features (torch.FloatTensor of shape (batch_size, output_dim)

引數

  • input_ids (torch.LongTensor of shape (batch_size * num_max_text_queries, sequence_length)) — 詞彙表中輸入序列標記的索引。可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什麼是輸入 ID?
  • attention_mask (torch.Tensor of shape (batch_size, sequence_length), optional) — 掩碼,以避免對填充標記索引執行注意力。掩碼值選自 [0, 1]

    • 1 表示未被遮蔽的標記,
    • 0 表示被遮蔽的標記。

    什麼是注意力掩碼?

  • output_attentions (bool, optional) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通的元組。

返回

text_features (torch.FloatTensor, 形狀為 (batch_size, output_dim)

透過將投影層應用於 OwlViTTextModel 的池化輸出而獲得的文字嵌入。

示例

>>> from transformers import AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> inputs = processor(
...     text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
... )
>>> text_features = model.get_text_features(**inputs)

get_image_features

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: bool = False return_dict: typing.Optional[bool] = None ) image_features (torch.FloatTensor,形狀為 (batch_size, output_dim))

引數

  • pixel_values (torch.FloatTensor,形狀為 (batch_size, num_channels, image_size, image_size), optional) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 處理影像)。
  • output_attentions (bool, optional) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • interpolate_pos_encoding (bool, 預設為 False) — 是否對預訓練的位置編碼進行插值。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通的元組。

返回

image_features (torch.FloatTensor, 形狀為 (batch_size, output_dim)

透過將投影層應用於 OwlViTVisionModel 的池化輸出而獲得的影像嵌入。

示例

>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, OwlViTModel

>>> model = OwlViTModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> inputs = processor(images=image, return_tensors="pt")
>>> image_features = model.get_image_features(**inputs)

OwlViTTextModel

class transformers.OwlViTTextModel

< >

( config: OwlViTTextConfig )

forward

< >

( input_ids: Tensor attention_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor,形狀為 (batch_size * num_max_text_queries, sequence_length)) — 詞彙表中輸入序列標記的索引。可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什麼是輸入 ID?
  • attention_mask (torch.Tensor,形狀為 (batch_size, sequence_length), optional) — 用於避免對填充標記索引執行注意力的掩碼。掩碼值選自 [0, 1]

    • 1 表示標記未被遮蓋
    • 0 表示標記被遮蓋

    什麼是注意力掩碼?

  • output_attentions (bool, optional) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通的元組。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一個 transformers.modeling_outputs.BaseModelOutputWithPooling 或一個 torch.FloatTensor 的元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),根據配置(OwlViTConfig)和輸入,包含各種元素。

  • last_hidden_state (torch.FloatTensor, 形狀為 (batch_size, sequence_length, hidden_size)) — 模型最後一層輸出的隱藏狀態序列。

  • pooler_output (torch.FloatTensor,形狀為 (batch_size, hidden_size)) — 序列的第一個標記(分類標記)的最後一層隱藏狀態,經過用於輔助預訓練任務的層進一步處理。例如,對於 BERT 家族模型,這返回分類標記經過線性層和 tanh 啟用函式處理後的結果。線性層權重是在預訓練期間透過下一句預測(分類)目標進行訓練的。

  • hidden_states (tuple(torch.FloatTensor), optional, 當傳遞 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — torch.FloatTensor 的元組(一個用於嵌入層的輸出,如果模型有嵌入層,+ 一個用於每層的輸出),形狀為 (batch_size, sequence_length, hidden_size)

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

  • attentions (tuple(torch.FloatTensor), optional, 當傳遞 output_attentions=Trueconfig.output_attentions=True 時返回) — torch.FloatTensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

OwlViTTextModel 的前向方法,重寫了 __call__ 特殊方法。

雖然前向傳播的流程需要在此函式內定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理預處理和後處理步驟,而後者會靜默地忽略它們。

示例

>>> from transformers import AutoProcessor, OwlViTTextModel

>>> model = OwlViTTextModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> inputs = processor(
...     text=[["a photo of a cat", "a photo of a dog"], ["photo of a astranaut"]], return_tensors="pt"
... )
>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled (EOS token) states

OwlViTVisionModel

class transformers.OwlViTVisionModel

< >

( config: OwlViTVisionConfig )

forward

< >

( pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: bool = False return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

引數

  • pixel_values (torch.FloatTensor,形狀為 (batch_size, num_channels, image_size, image_size), optional) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 處理影像)。
  • output_attentions (bool, optional) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • interpolate_pos_encoding (bool, 預設為 False) — 是否對預訓練的位置編碼進行插值。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通的元組。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一個 transformers.modeling_outputs.BaseModelOutputWithPooling 或一個 torch.FloatTensor 的元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),根據配置(OwlViTConfig)和輸入,包含各種元素。

  • last_hidden_state (torch.FloatTensor, 形狀為 (batch_size, sequence_length, hidden_size)) — 模型最後一層輸出的隱藏狀態序列。

  • pooler_output (torch.FloatTensor,形狀為 (batch_size, hidden_size)) — 序列的第一個標記(分類標記)的最後一層隱藏狀態,經過用於輔助預訓練任務的層進一步處理。例如,對於 BERT 家族模型,這返回分類標記經過線性層和 tanh 啟用函式處理後的結果。線性層權重是在預訓練期間透過下一句預測(分類)目標進行訓練的。

  • hidden_states (tuple(torch.FloatTensor), optional, 當傳遞 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — torch.FloatTensor 的元組(一個用於嵌入層的輸出,如果模型有嵌入層,+ 一個用於每層的輸出),形狀為 (batch_size, sequence_length, hidden_size)

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

  • attentions (tuple(torch.FloatTensor), optional, 當傳遞 output_attentions=Trueconfig.output_attentions=True 時返回) — torch.FloatTensor 的元組(每層一個),形狀為 (batch_size, num_heads, sequence_length, sequence_length)

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

OwlViTVisionModel 的前向方法,重寫了 __call__ 特殊方法。

雖然前向傳播的流程需要在此函式內定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理預處理和後處理步驟,而後者會靜默地忽略它們。

示例

>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, OwlViTVisionModel

>>> model = OwlViTVisionModel.from_pretrained("google/owlvit-base-patch32")
>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch32")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> inputs = processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)
>>> last_hidden_state = outputs.last_hidden_state
>>> pooled_output = outputs.pooler_output  # pooled CLS states

OwlViTForObjectDetection

class transformers.OwlViTForObjectDetection

< >

( config: OwlViTConfig )

forward

< >

( input_ids: Tensor pixel_values: FloatTensor attention_mask: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: bool = False return_dict: typing.Optional[bool] = None ) transformers.models.owlvit.modeling_owlvit.OwlViTObjectDetectionOutputtuple(torch.FloatTensor)

引數

  • input_ids (torch.LongTensor,形狀為 (batch_size * num_max_text_queries, sequence_length), optional) — 詞彙表中輸入序列標記的索引。可以使用 AutoTokenizer 獲取索引。有關詳細資訊,請參閱 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什麼是輸入 ID?
  • pixel_values (torch.FloatTensor,形狀為 (batch_size, num_channels, image_size, image_size)) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 處理影像)。
  • attention_mask (torch.Tensor,形狀為 (batch_size, sequence_length), optional) — 用於避免對填充標記索引執行注意力的掩碼。掩碼值選自 [0, 1]

    • 1 表示標記未被遮蓋
    • 0 表示標記被遮蓋

    什麼是注意力掩碼?

  • output_attentions (bool, optional) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回最後一個隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 text_model_last_hidden_statevision_model_last_hidden_state
  • interpolate_pos_encoding (bool, 預設為 False) — 是否對預訓練的位置編碼進行插值。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通的元組。

返回

transformers.models.owlvit.modeling_owlvit.OwlViTObjectDetectionOutputtuple(torch.FloatTensor)

一個 transformers.models.owlvit.modeling_owlvit.OwlViTObjectDetectionOutput 或一個 torch.FloatTensor 的元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),根據配置(OwlViTConfig)和輸入,包含各種元素。

  • loss (torch.FloatTensor,形狀為 (1,), optional, 當提供 labels 時返回) — 總損失,是類別預測的負對數似然(交叉熵)和邊界框損失的線性組合。後者定義為 L1 損失和廣義尺度不變 IoU 損失的線性組合。
  • loss_dict (Dict, 可選) — 包含各個損失的字典。用於日誌記錄。
  • logits (torch.FloatTensor,形狀為 (batch_size, num_patches, num_queries)) — 所有查詢的分類 logits(包括無物件)。
  • pred_boxes (torch.FloatTensor,形狀為 (batch_size, num_patches, 4)) — 所有查詢的歸一化框座標,表示為 (center_x, center_y, width, height)。這些值在 [0, 1] 範圍內歸一化,相對於批次中每個單獨影像的大小(忽略可能的填充)。您可以使用 post_process_object_detection() 來檢索未歸一化的邊界框。
  • text_embeds (torch.FloatTensor,形狀為 (batch_size, num_max_text_queries, output_dim)) — 透過將投影層應用於 OwlViTTextModel 的池化輸出而獲得的文字嵌入。
  • image_embeds (torch.FloatTensor,形狀為 (batch_size, patch_size, patch_size, output_dim)) — OwlViTVisionModel 的池化輸出。OWL-ViT 將影像表示為一組影像塊,併為每個塊計算影像嵌入。
  • class_embeds (torch.FloatTensor,形狀為 (batch_size, num_patches, hidden_size)) — 所有影像塊的類別嵌入。OWL-ViT 將影像表示為一組影像塊,其中總塊數為 (image_size / patch_size)**2。
  • text_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output, defaults to None) — OwlViTTextModel 的輸出。
  • vision_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output, defaults to None) — OwlViTVisionModel 的輸出。

OwlViTForObjectDetection 的前向方法,重寫了 __call__ 特殊方法。

雖然前向傳播的流程需要在此函式內定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理預處理和後處理步驟,而後者會靜默地忽略它們。

示例

>>> import requests
>>> from PIL import Image
>>> import torch

>>> from transformers import OwlViTProcessor, OwlViTForObjectDetection

>>> processor = OwlViTProcessor.from_pretrained("google/owlvit-base-patch32")
>>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch32")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text_labels = [["a photo of a cat", "a photo of a dog"]]
>>> inputs = processor(text=text_labels, images=image, return_tensors="pt")
>>> outputs = model(**inputs)

>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.tensor([(image.height, image.width)])
>>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> results = processor.post_process_grounded_object_detection(
...     outputs=outputs, target_sizes=target_sizes, threshold=0.1, text_labels=text_labels
... )
>>> # Retrieve predictions for the first image for the corresponding text queries
>>> result = results[0]
>>> boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
>>> for box, score, text_label in zip(boxes, scores, text_labels):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected a photo of a cat with confidence 0.707 at location [324.97, 20.44, 640.58, 373.29]
Detected a photo of a cat with confidence 0.717 at location [1.46, 55.26, 315.55, 472.17]

image_guided_detection

< >

( pixel_values: FloatTensor query_pixel_values: typing.Optional[torch.FloatTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None interpolate_pos_encoding: bool = False return_dict: typing.Optional[bool] = None ) transformers.models.owlvit.modeling_owlvit.OwlViTImageGuidedObjectDetectionOutputtuple(torch.FloatTensor)

引數

  • pixel_values (torch.FloatTensor,形狀為 (batch_size, num_channels, image_size, image_size)) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 處理影像)。
  • query_pixel_values (torch.FloatTensor,形狀為 (batch_size, num_channels, height, width)) — 要檢測的查詢影像的畫素值。為每個目標影像傳入一個查詢影像。
  • output_attentions (bool, optional) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參閱返回張量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • interpolate_pos_encoding (bool, 預設為 False) — 是否對預訓練的位置編碼進行插值。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通的元組。

返回

transformers.models.owlvit.modeling_owlvit.OwlViTImageGuidedObjectDetectionOutputtuple(torch.FloatTensor)

一個 transformers.models.owlvit.modeling_owlvit.OwlViTImageGuidedObjectDetectionOutput 或一個 torch.FloatTensor 的元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),根據配置(OwlViTConfig)和輸入,包含各種元素。

  • logits (torch.FloatTensor,形狀為 (batch_size, num_patches, num_queries)) — 所有查詢的分類 logits(包括無物件)。
  • image_embeds (torch.FloatTensor,形狀為 (batch_size, patch_size, patch_size, output_dim)) — OwlViTVisionModel 的池化輸出。OWL-ViT 將影像表示為一組影像塊,併為每個塊計算影像嵌入。
  • query_image_embeds (torch.FloatTensor,形狀為 (batch_size, patch_size, patch_size, output_dim)) — OwlViTVisionModel 的池化輸出。OWL-ViT 將影像表示為一組影像塊,併為每個塊計算影像嵌入。
  • target_pred_boxes (torch.FloatTensor,形狀為 (batch_size, num_patches, 4)) — 所有查詢的歸一化框座標,表示為 (center_x, center_y, width, height)。這些值在 [0, 1] 範圍內歸一化,相對於批次中每個單獨目標影像的大小(忽略可能的填充)。您可以使用 post_process_object_detection() 來檢索未歸一化的邊界框。
  • query_pred_boxes (torch.FloatTensor,形狀為 (batch_size, num_patches, 4)) — 所有查詢的歸一化框座標,表示為 (center_x, center_y, width, height)。這些值在 [0, 1] 範圍內歸一化,相對於批次中每個單獨查詢影像的大小(忽略可能的填充)。您可以使用 post_process_object_detection() 來檢索未歸一化的邊界框。
  • class_embeds (torch.FloatTensor,形狀為 (batch_size, num_patches, hidden_size)) — 所有影像塊的類別嵌入。OWL-ViT 將影像表示為一組影像塊,其中總塊數為 (image_size / patch_size)**2。
  • text_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output, defaults to None) — OwlViTTextModel 的輸出。
  • vision_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output, defaults to None) — OwlViTVisionModel 的輸出。

示例

>>> import requests
>>> from PIL import Image
>>> import torch
>>> from transformers import AutoProcessor, OwlViTForObjectDetection

>>> processor = AutoProcessor.from_pretrained("google/owlvit-base-patch16")
>>> model = OwlViTForObjectDetection.from_pretrained("google/owlvit-base-patch16")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> query_url = "http://images.cocodataset.org/val2017/000000001675.jpg"
>>> query_image = Image.open(requests.get(query_url, stream=True).raw)
>>> inputs = processor(images=image, query_images=query_image, return_tensors="pt")
>>> with torch.no_grad():
...     outputs = model.image_guided_detection(**inputs)
>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.Tensor([image.size[::-1]])
>>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> results = processor.post_process_image_guided_detection(
...     outputs=outputs, threshold=0.6, nms_threshold=0.3, target_sizes=target_sizes
... )
>>> i = 0  # Retrieve predictions for the first image
>>> boxes, scores = results[i]["boxes"], results[i]["scores"]
>>> for box, score in zip(boxes, scores):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected similar object with confidence {round(score.item(), 3)} at location {box}")
Detected similar object with confidence 0.856 at location [10.94, 50.4, 315.8, 471.39]
Detected similar object with confidence 1.0 at location [334.84, 25.33, 636.16, 374.71]
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.