Transformers 文件
OWLv2
並獲得增強的文件體驗
開始使用
OWLv2
概述
OWLv2 由 Matthias Minderer、Alexey Gritsenko 和 Neil Houlsby 在論文 《擴充套件開放詞彙目標檢測》(Scaling Open-Vocabulary Object Detection) 中提出。OWLv2 使用自訓練方法擴充套件了 OWL-ViT,該方法利用現有檢測器在圖文對上生成偽框標註。這使得其在零樣本目標檢測方面比之前的 SOTA 模型取得了巨大進步。
論文摘要如下:
開放詞彙目標檢測極大地受益於預訓練的視覺語言模型,但仍然受限於可用的檢測訓練資料量。雖然可以透過使用網路圖文對作為弱監督來擴充套件檢測訓練資料,但這並未在與影像級預訓練相當的規模上進行。在這裡,我們透過自訓練來擴充套件檢測資料,該方法使用現有檢測器在圖文對上生成偽框標註。擴充套件自訓練的主要挑戰是標籤空間的選擇、偽標註的過濾和訓練效率。我們提出了 OWLv2 模型和 OWL-ST 自訓練配方,解決了這些挑戰。在相當的訓練規模(約 1000 萬個樣本)下,OWLv2 的效能已經超過了之前最先進的開放詞彙檢測器。然而,透過 OWL-ST,我們可以擴充套件到超過 10 億個樣本,從而帶來更大的提升:使用 L/14 架構,OWL-ST 將 LVIS 稀有類別的 AP 從 31.2% 提高到 44.6%(相對提升 43%),而模型並未見過這些類別的人工框標註。OWL-ST 為開放世界定位解鎖了網路規模的訓練,類似於在影像分類和語言建模中看到的情況。

用法示例
OWLv2 和其前身 OWL-ViT 一樣,是一個零樣本文字條件的目標檢測模型。OWL-ViT 使用 CLIP 作為其多模態主幹,透過一個類 ViT 的 Transformer 獲取視覺特徵,透過一個因果語言模型獲取文字特徵。為了將 CLIP 用於檢測,OWL-ViT 移除了視覺模型的最終 token 池化層,並在每個 Transformer 輸出 token 上附加了一個輕量級的分類和框頭。透過將固定的分類層權重替換為從文字模型獲得的類名嵌入,實現了開放詞彙分類。作者首先從頭開始訓練 CLIP,然後將其與分類和框頭在標準檢測資料集上進行端到端的微調,使用二分匹配損失。每張影像可以使用一個或多個文字查詢來執行零樣本文字條件的目標檢測。
Owlv2ImageProcessor 可用於調整影像大小(或縮放)和歸一化,而 CLIPTokenizer 用於編碼文字。Owlv2Processor 將 Owlv2ImageProcessor 和 CLIPTokenizer 包裝成一個單一例項,以同時編碼文字和準備影像。以下示例展示瞭如何使用 Owlv2Processor 和 Owlv2ForObjectDetection 進行目標檢測。
>>> import requests
>>> from PIL import Image
>>> import torch
>>> from transformers import Owlv2Processor, Owlv2ForObjectDetection
>>> processor = Owlv2Processor.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> 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.614 at location [341.67, 23.39, 642.32, 371.35]
Detected a photo of a cat with confidence 0.665 at location [6.75, 51.96, 326.62, 473.13]
資源
- 一個關於使用 OWLv2 進行零樣本和單樣本(影像引導)目標檢測的演示筆記本可以在此處找到。
- 零樣本目標檢測任務指南
OWLv2 的架構與 OWL-ViT 相同,但目標檢測頭現在還包括一個物體性分類器,用於預測預測框包含物體(而不是背景)的(與查詢無關的)可能性。物體性得分可用於獨立於文字查詢對預測進行排序或過濾。OWLv2 的使用方法與 OWL-ViT 相同,但使用了新的、更新的影像處理器(Owlv2ImageProcessor)。
Owlv2Config
class transformers.Owlv2Config
< 原始碼 >( text_config = None vision_config = None projection_dim = 512 logit_scale_init_value = 2.6592 return_dict = True **kwargs )
引數
- text_config (
dict
, 可選) — 用於初始化 Owlv2TextConfig 的配置選項字典。 - vision_config (
dict
, 可選) — 用於初始化 Owlv2VisionConfig 的配置選項字典。 - projection_dim (
int
, 可選, 預設為 512) — 文字和視覺投影層的維度。 - logit_scale_init_value (
float
, 可選, 預設為 2.6592) — logit_scale 引數的初始值。預設值根據原始 OWLv2 實現使用。 - return_dict (
bool
, 可選, 預設為True
) — 模型是否應返回一個字典。如果為False
,則返回一個元組。 - kwargs (可選) — 關鍵字引數字典。
Owlv2Config 是用於儲存 Owlv2Model 配置的配置類。它用於根據指定的引數例項化一個 OWLv2 模型,定義文字模型和視覺模型的配置。使用預設值例項化配置將產生與 OWLv2 google/owlv2-base-patch16 架構類似的配置。
配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。
from_text_vision_configs
< 原始碼 >( text_config: dict vision_config: dict **kwargs ) → Owlv2Config
根據 owlv2 文字模型配置和 owlv2 視覺模型配置例項化一個 Owlv2Config(或其派生類)。
Owlv2TextConfig
class transformers.Owlv2TextConfig
< 原始碼 >( 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) — OWLv2 文字模型的詞彙表大小。定義了在呼叫 Owlv2TextModel 時傳遞的inputs_ids
可以表示的不同 token 的數量。 - 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 (
str
或function
, 可選, 預設為"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) — 輸入序列中填充 token 的 id。 - bos_token_id (
int
, 可選, 預設為 49406) — 輸入序列中序列開始 token 的 id。 - eos_token_id (
int
, 可選, 預設為 49407) — 輸入序列中序列結束 token 的 id。
這是用於儲存 Owlv2TextModel 配置的配置類。它用於根據指定的引數例項化一個 Owlv2 文字編碼器,定義模型架構。使用預設值例項化配置將產生與 Owlv2 google/owlv2-base-patch16 架構類似的配置。
配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。
示例
>>> from transformers import Owlv2TextConfig, Owlv2TextModel
>>> # Initializing a Owlv2TextModel with google/owlv2-base-patch16 style configuration
>>> configuration = Owlv2TextConfig()
>>> # Initializing a Owlv2TextConfig from the google/owlv2-base-patch16 style configuration
>>> model = Owlv2TextModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
Owlv2VisionConfig
class transformers.Owlv2VisionConfig
< 原始碼 >( hidden_size = 768 intermediate_size = 3072 num_hidden_layers = 12 num_attention_heads = 12 num_channels = 3 image_size = 768 patch_size = 16 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
, 可選, 預設為 16) — 每個補丁(patch)的大小(解析度)。 - hidden_act (
str
orfunction
, 可選, 預設為"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,內部用於初始化測試)。
這是用於儲存 Owlv2VisionModel 配置的配置類。它根據指定的引數例項化一個 OWLv2 影像編碼器,定義模型架構。使用預設值例項化配置將產生與 OWLv2 google/owlv2-base-patch16 架構相似的配置。
配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。
示例
>>> from transformers import Owlv2VisionConfig, Owlv2VisionModel
>>> # Initializing a Owlv2VisionModel with google/owlv2-base-patch16 style configuration
>>> configuration = Owlv2VisionConfig()
>>> # Initializing a Owlv2VisionModel model from the google/owlv2-base-patch16 style configuration
>>> model = Owlv2VisionModel(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
Owlv2ImageProcessor
class transformers.Owlv2ImageProcessor
< source >( do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_pad: bool = True do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None **kwargs )
引數
- do_rescale (
bool
, 可選, 預設為True
) — 是否透過指定的比例 `rescale_factor` 來縮放影像。可以在 `preprocess` 方法中透過 `do_rescale` 覆蓋。 - rescale_factor (
int
orfloat
, 可選, 預設為1/255
) — 如果縮放影像,則使用的比例因子。可以在 `preprocess` 方法中透過 `rescale_factor` 覆蓋。 - do_pad (
bool
, 可選, 預設為True
) — 是否在底部和右側用灰色畫素將影像填充為正方形。可以在 `preprocess` 方法中透過 `do_pad` 覆蓋。 - do_resize (
bool
, 可選, 預設為True
) — 控制是否將影像的(高度,寬度)尺寸調整為指定的 `size`。可以在 `preprocess` 方法中透過 `do_resize` 覆蓋。 - size (
dict[str, int]
, 可選, 預設為{"height": 960, "width": 960}
):要將影像調整到的大小。可以在 `preprocess` 方法中透過 `size` 覆蓋。 - resample (
PILImageResampling
, 可選, 預設為Resampling.BILINEAR
) — 如果調整影像大小,則使用的重取樣方法。可以在 `preprocess` 方法中透過 `resample` 覆蓋。 - do_normalize (
bool
, 可選, 預設為True
) — 是否對影像進行歸一化。可以在 `preprocess` 方法中透過 `do_normalize` 引數覆蓋。 - image_mean (
float
orlist[float]
, 可選, 預設為OPENAI_CLIP_MEAN
) — 如果對影像進行歸一化,則使用的均值。這是一個浮點數或長度等於影像通道數的浮點數列表。可以在 `preprocess` 方法中透過 `image_mean` 引數覆蓋。 - image_std (
float
orlist[float]
, 可選, 預設為OPENAI_CLIP_STD
) — 如果對影像進行歸一化,則使用的標準差。這是一個浮點數或長度等於影像通道數的浮點數列表。可以在 `preprocess` 方法中透過 `image_std` 引數覆蓋。
構建一個 OWLv2 影像處理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_pad: typing.Optional[bool] = None do_resize: typing.Optional[bool] = None 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[str, transformers.utils.generic.TensorType, NoneType] = None data_format: 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_pad (
bool
, 可選, 預設為self.do_pad
) — 是否在底部和右側用灰色畫素將影像填充為正方形。 - do_resize (
bool
, 可選, 預設為self.do_resize
) — 是否調整影像大小。 - size (
dict[str, int]
, 可選, 預設為self.size
) — 要將影像調整到的大小。 - do_rescale (
bool
, 可選, 預設為self.do_rescale
) — 是否將影像值縮放到 [0 - 1] 之間。 - rescale_factor (
float
, 可選, 預設為self.rescale_factor
) — 如果 `do_rescale` 設定為 `True`,則用於縮放影像的比例因子。 - do_normalize (
bool
, 可選, 預設為self.do_normalize
) — 是否對影像進行歸一化。 - image_mean (
float
orlist[float]
, 可選, 預設為self.image_mean
) — 影像均值。 - image_std (
float
orlist[float]
, 可選, 預設為self.image_std
) — 影像標準差。 - return_tensors (
str
orTensorType
, 可選) — 要返回的張量型別。可以是以下之一:- 未設定:返回
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
orstr
, 可選, 預設為ChannelDimension.FIRST
) — 輸出影像的通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:影像格式為 (height, width, num_channels)。- 未設定:使用輸入影像的通道維度格式。
- input_data_format (
ChannelDimension
orstr
, 可選) — 輸入影像的通道維度格式。如果未設定,則從輸入影像中推斷通道維度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:影像格式為 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:影像格式為 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:影像格式為 (height, width)。
預處理一張或一批影像。
post_process_object_detection
< source >( outputs: Owlv2ObjectDetectionOutput threshold: float = 0.1 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None ) → list[Dict]
引數
- outputs (
Owlv2ObjectDetectionOutput
) — 模型的原始輸出。 - threshold (
float
, 可選, 預設為 0.1) — 用於保留目標檢測預測結果的分數閾值。 - target_sizes (
torch.Tensor
orlist[tuple[int, int]]
, 可選) — 形狀為 `(batch_size, 2)` 的張量或元組列表 (`tuple[int, int]`),包含批次中每個影像的目標尺寸 `(height, width)`。如果未設定,預測結果將不會被調整大小。
返回
list[Dict]
一個字典列表,每個字典包含以下鍵:
- “scores”:影像上每個預測框的置信度分數。
- “labels”:模型在影像上預測的類別索引。
- “boxes”:影像邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
將 Owlv2ForObjectDetection 的原始輸出轉換為最終的邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
post_process_image_guided_detection
< source >( outputs threshold = 0.0 nms_threshold = 0.3 target_sizes = None ) → list[Dict]
引數
- outputs (
OwlViTImageGuidedObjectDetectionOutput
) — 模型的原始輸出。 - threshold (
float
, 可選, 預設為 0.0) — 用於過濾預測框的最低置信度閾值。 - nms_threshold (
float
, 可選, 預設為 0.3) — 用於非極大值抑制重疊框的 IoU 閾值。 - target_sizes (
torch.Tensor
, 可選) — 形狀為 (batch_size, 2) 的張量,其中每個條目是批次中對應影像的 (height, width)。如果設定,預測的歸一化邊界框將被重新縮放到目標尺寸。如果留空為 None,預測結果將不會被反歸一化。
返回
list[Dict]
一個字典列表,每個字典包含模型為批次中一個影像預測的分數、標籤和邊界框。所有標籤都設定為 None,因為 `OwlViTForObjectDetection.image_guided_detection` 執行的是一次性目標檢測。
將 OwlViTForObjectDetection.image_guided_detection() 的輸出轉換為 COCO API 預期的格式。
Owlv2Processor
class transformers.Owlv2Processor
< source >( image_processor tokenizer **kwargs )
引數
- image_processor (Owlv2ImageProcessor) — 影像處理器是必需的輸入。
- tokenizer ([
CLIPTokenizer
,CLIPTokenizerFast
]) — 分詞器是必需的輸入。
構建一個 Owlv2 處理器,它將 Owlv2ImageProcessor 和 CLIPTokenizer/CLIPTokenizerFast 包裝成一個單一的處理器,該處理器繼承了影像處理器和分詞器的功能。有關更多資訊,請參閱 call() 和 `decode()` 方法。
__call__
< source >( 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.owlv2.processing_owlv2.Owlv2ProcessorKwargs] ) → 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, 可選) — 如果設定,將返回特定框架的張量。可接受的值包括:'tf'
: 返回 TensorFlowtf.constant
物件。'pt'
: 返回 PyTorchtorch.Tensor
物件。'np'
: 返回 NumPynp.ndarray
物件。'jax'
: 返回 JAXjnp.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` 時返回。
為模型準備一個或多個文字和影像的主要方法。如果 `text` 不為 `None`,此方法將 `text` 和 `kwargs` 引數轉發到 CLIPTokenizerFast 的 call() 方法以編碼文字。如果 `images` 不為 `None`,此方法將 `images` 和 `kwrags` 引數轉發到 CLIPImageProcessor 的 call() 方法以準備影像。有關更多資訊,請參閱上述兩個方法的文件字串。
post_process_grounded_object_detection
< source >( outputs: Owlv2ObjectDetectionOutput 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 (
Owlv2ObjectDetectionOutput
) — 模型的原始輸出。 - threshold (
float
, 可選, 預設為 0.1) — 用於保留目標檢測預測的分數閾值。 - target_sizes (
torch.Tensor
或list[tuple[int, int]]
, 可選) — 形狀為(batch_size, 2)
的張量或元組列表 (tuple[int, int]
),包含批次中每張影像的目標尺寸(高度, 寬度)
。如果未設定,預測結果將不會被調整大小。 - text_labels (
list[list[str]]
, 可選) — 批次中每張影像的文字標籤列表的列表。如果未設定,輸出中的“text_labels”將被設定為None
。
返回
list[Dict]
一個字典列表,每個字典包含以下鍵:
- “scores”:影像上每個預測框的置信度分數。
- “labels”:模型在影像上預測的類別索引。
- “boxes”:影像邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
- “text_labels”:影像上每個預測邊界框的文字標籤。
將 Owlv2ForObjectDetection 的原始輸出轉換為最終的邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
post_process_image_guided_detection
< source >( outputs: Owlv2ImageGuidedObjectDetectionOutput threshold: float = 0.0 nms_threshold: float = 0.3 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None ) → list[Dict]
引數
- outputs (
Owlv2ImageGuidedObjectDetectionOutput
) — 模型的原始輸出。 - threshold (
float
, 可選, 預設為 0.0) — 用於過濾預測框的最低置信度閾值。 - nms_threshold (
float
, 可選, 預設為 0.3) — 用於非極大值抑制重疊框的 IoU 閾值。 - target_sizes (
torch.Tensor
, 可選) — 形狀為 (batch_size, 2) 的張量,其中每個條目是批次中相應影像的 (高度, 寬度)。如果設定,預測的歸一化邊界框將重新縮放到目標尺寸。如果保持為 None,預測將不會被反歸一化。
返回
list[Dict]
一個字典列表,每個字典包含以下鍵:
- “scores”:影像上每個預測框的置信度分數。
- “boxes”:影像邊界框,格式為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
- “labels”:設定為
None
。
將 Owlv2ForObjectDetection.image_guided_detection() 的輸出轉換為 COCO API 所期望的格式。
Owlv2Model
class transformers.Owlv2Model
< source >( config: Owlv2Config )
引數
- config (Owlv2Config) — 模型配置類,包含模型的所有引數。使用配置檔案初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
基礎的 Owlv2 模型,輸出原始的隱藏狀態,頂部沒有任何特定的頭。
該模型繼承自 PreTrainedModel。請檢視超類文件以瞭解該庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。
此模型也是 PyTorch torch.nn.Module 的子類。可以像常規 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與常規用法和行為相關的事項。
forward
< source >( 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.owlv2.modeling_owlv2.Owlv2Output
或 tuple(torch.FloatTensor)
引數
- input_ids (
torch.LongTensor
,形狀為(batch_size, sequence_length)
, 可選) — 詞彙表中輸入序列標記的索引。預設情況下,填充將被忽略。索引可以使用 AutoTokenizer 獲得。有關詳細資訊,請參閱 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
- 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)
, 可選) — 用於避免對填充標記索引執行注意力操作的掩碼。掩碼值在[0, 1]
中選擇:- 1 表示標記未被掩碼,
- 0 表示標記被掩碼。
- return_loss (
bool
, 可選) — 是否返回對比損失。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量下的 `attentions`。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量下的 `hidden_states`。 - interpolate_pos_encoding (
bool
, 預設為False
) — 是否對預訓練的位置編碼進行插值。 - return_base_image_embeds (
bool
, 可選) — 是否返回基礎影像嵌入。 - return_dict (
bool
, 可選) — 是返回一個 ModelOutput 而不是一個普通的元組。
返回
transformers.models.owlv2.modeling_owlv2.Owlv2Output
或 tuple(torch.FloatTensor)
一個 transformers.models.owlv2.modeling_owlv2.Owlv2Output
或一個 `torch.FloatTensor` 的元組(如果傳遞 `return_dict=False` 或當 `config.return_dict=False` 時),根據配置 (Owlv2Config) 和輸入包含不同的元素。
- loss (
torch.FloatTensor
,形狀為(1,)
, 可選, 當return_loss
為True
時返回) — 影像-文字相似度的對比損失。 - logits_per_image (
torch.FloatTensor
,形狀為(image_batch_size, text_batch_size)
) —image_embeds
和text_embeds
之間的縮放點積得分。這表示影像-文字相似性得分。 - logits_per_text (
torch.FloatTensor
,形狀為(text_batch_size, image_batch_size)
) —text_embeds
和image_embeds
之間的縮放點積得分。這表示文字-影像相似性得分。 - text_embeds (
torch.FloatTensor
,形狀為(batch_size * num_max_text_queries, output_dim)
) — 透過將投影層應用於 Owlv2TextModel 的池化輸出獲得的文字嵌入。 - image_embeds (
torch.FloatTensor
,形狀為(batch_size, output_dim)
) — 透過將投影層應用於 Owlv2VisionModel 的池化輸出獲得的影像嵌入。 - text_model_output (
<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output
, 預設為None
) — Owlv2TextModel 的輸出。 - vision_model_output (
<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output
, 預設為None
) — Owlv2VisionModel 的輸出。
Owlv2Model 的 forward 方法,覆蓋了 `__call__` 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 `Module` 例項而不是此函式,因為前者會處理執行前處理和後處理步驟,而後者會默默地忽略它們。
示例
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Owlv2Model
>>> model = Owlv2Model.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> processor = AutoProcessor.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> 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
< source >( 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
,形狀為 (batch_size, output_dim)
)
引數
- 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)
, 可選) — 用於避免對填充標記索引執行注意力操作的掩碼。掩碼值在[0, 1]
中選擇:- 1 表示標記未被掩碼,
- 0 表示標記被掩碼。
- output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量下的 `attentions`。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量下的 `hidden_states`。 - return_dict (
bool
, 可選) — 是返回一個 ModelOutput 而不是一個普通的元組。
返回
text_features (torch.FloatTensor
, 形狀為 (batch_size, output_dim
)
透過將投影層應用於 Owlv2TextModel 的池化輸出獲得的文字嵌入。
示例
>>> from transformers import AutoProcessor, Owlv2Model
>>> model = Owlv2Model.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> processor = AutoProcessor.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> 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
< source >( 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)
, 可選) — 對應於輸入影像的張量。畫素值可以使用{image_processor_class}
獲得。有關詳細資訊,請參閱{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
處理影像)。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量下的 `attentions`。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量下的 `hidden_states`。 - interpolate_pos_encoding (
bool
, 預設為False
) — 是否對預訓練的位置編碼進行插值。 - return_dict (
bool
, 可選) — 是返回一個 ModelOutput 而不是一個普通的元組。
返回
image_features (torch.FloatTensor
, 形狀為 (batch_size, output_dim
)
透過將投影層應用於 Owlv2VisionModel 的池化輸出獲得的影像嵌入。
示例
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Owlv2Model
>>> model = Owlv2Model.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> processor = AutoProcessor.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> 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)
Owlv2TextModel
forward
< source >( 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.BaseModelOutputWithPooling 或 tuple(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)
, 可選) — 用於避免對填充標記索引執行注意力操作的掩碼。掩碼值在[0, 1]
中選擇:- 1 表示標記未被掩碼,
- 0 表示標記被掩碼。
- output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量下的 `attentions`。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量下的 `hidden_states`。 - return_dict (
bool
, 可選) — 是返回一個 ModelOutput 而不是一個普通的元組。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一個 transformers.modeling_outputs.BaseModelOutputWithPooling 或一個 `torch.FloatTensor` 的元組(如果傳遞 `return_dict=False` 或當 `config.return_dict=False` 時),根據配置 (Owlv2Config) 和輸入包含不同的元素。
-
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)
, 可選, 當傳遞 `output_hidden_states=True` 或當 `config.output_hidden_states=True` 時返回) — `torch.FloatTensor` 的元組(如果模型有嵌入層,則一個用於嵌入層的輸出,+ 每個層的一個輸出),形狀為 `(batch_size, sequence_length, hidden_size)`。模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。
-
attentions (
tuple(torch.FloatTensor)
, 可選, 當傳遞 `output_attentions=True` 或當 `config.output_attentions=True` 時返回) — `torch.FloatTensor` 的元組(每層一個),形狀為 `(batch_size, num_heads, sequence_length, sequence_length)`。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。
Owlv2TextModel 的 forward 方法,覆蓋了 `__call__` 特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 `Module` 例項而不是此函式,因為前者會處理執行前處理和後處理步驟,而後者會默默地忽略它們。
示例
>>> from transformers import AutoProcessor, Owlv2TextModel
>>> model = Owlv2TextModel.from_pretrained("google/owlv2-base-patch16")
>>> processor = AutoProcessor.from_pretrained("google/owlv2-base-patch16")
>>> 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
Owlv2VisionModel
forward
< source >( 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.BaseModelOutputWithPooling 或 tuple(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}
處理影像)。 - output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量下的 `attentions`。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量下的 `hidden_states`。 - interpolate_pos_encoding (
bool
, 預設為False
) — 是否對預訓練的位置編碼進行插值。 - return_dict (
bool
, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。
返回
transformers.modeling_outputs.BaseModelOutputWithPooling 或 tuple(torch.FloatTensor)
一個 transformers.modeling_outputs.BaseModelOutputWithPooling 或一個 `torch.FloatTensor` 的元組(如果傳遞 `return_dict=False` 或當 `config.return_dict=False` 時),根據配置 (Owlv2Config) 和輸入包含不同的元素。
-
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)
, 可選, 當傳遞 `output_hidden_states=True` 或當 `config.output_hidden_states=True` 時返回) — `torch.FloatTensor` 的元組(如果模型有嵌入層,則一個用於嵌入層的輸出,+ 每個層的一個輸出),形狀為 `(batch_size, sequence_length, hidden_size)`。模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。
-
attentions (
tuple(torch.FloatTensor)
, 可選, 當傳遞 `output_attentions=True` 或當 `config.output_attentions=True` 時返回) — `torch.FloatTensor` 的元組(每層一個),形狀為 `(batch_size, num_heads, sequence_length, sequence_length)`。注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。
Owlv2VisionModel 的 forward 方法會覆蓋 __call__
特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 `Module` 例項而不是此函式,因為前者會處理執行前處理和後處理步驟,而後者會默默地忽略它們。
示例
>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, Owlv2VisionModel
>>> model = Owlv2VisionModel.from_pretrained("google/owlv2-base-patch16")
>>> processor = AutoProcessor.from_pretrained("google/owlv2-base-patch16")
>>> 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
Owlv2ForObjectDetection
forward
< source >( 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.owlv2.modeling_owlv2.Owlv2ObjectDetectionOutput
或 tuple(torch.FloatTensor)
引數
- input_ids (
torch.LongTensor
,形狀為(batch_size * num_max_text_queries, sequence_length)
, 可選) — 詞彙表中輸入序列標記的索引。可以使用 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)
, 可選) — 用於避免在填充標記索引上執行注意力操作的掩碼。掩碼值在[0, 1]
中選擇:- 對於未被遮蔽的標記為 1,
- 對於被遮蔽的標記為 0。
- output_attentions (
bool
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量下的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回最後一個隱藏狀態。有關詳細資訊,請參閱返回張量下的text_model_last_hidden_state
和vision_model_last_hidden_state
。 - interpolate_pos_encoding (
bool
, 預設為False
) — 是否對預訓練的位置編碼進行插值。 - return_dict (
bool
, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。
返回
transformers.models.owlv2.modeling_owlv2.Owlv2ObjectDetectionOutput
或 tuple(torch.FloatTensor)
一個 transformers.models.owlv2.modeling_owlv2.Owlv2ObjectDetectionOutput
或一個 torch.FloatTensor
的元組(如果傳遞了 return_dict=False
或 config.return_dict=False
),根據配置(Owlv2Config)和輸入,包含各種元素。
- loss (
torch.FloatTensor
,形狀為(1,)
, 可選, 當提供labels
時返回) — 總損失,是用於類別預測的負對數似然(交叉熵)和邊界框損失的線性組合。後者定義為 L1 損失和廣義尺度不變 IoU 損失的線性組合。 - loss_dict (
Dict
, 可選) — 包含各個損失的字典。用於日誌記錄。 - logits (
torch.FloatTensor
,形狀為(batch_size, num_patches, num_queries)
) — 所有查詢的分類 logits(包括無物件)。 - objectness_logits (
torch.FloatTensor
,形狀為(batch_size, num_patches, 1)
) — 所有影像塊的物件性 logits。OWL-ViT 將影像表示為一組影像塊,其中塊的總數為 (image_size / patch_size)**2。 - 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)
) — 透過將投影層應用於 Owlv2TextModel 的池化輸出而獲得的文字嵌入。 - image_embeds (
torch.FloatTensor
,形狀為(batch_size, patch_size, patch_size, output_dim)
) — Owlv2VisionModel 的池化輸出。OWLv2 將影像表示為一組影像塊,併為每個塊計算影像嵌入。 - class_embeds (
torch.FloatTensor
,形狀為(batch_size, num_patches, hidden_size)
) — 所有影像塊的類別嵌入。OWLv2 將影像表示為一組影像塊,其中塊的總數為 (image_size / patch_size)**2。 - text_model_output (
<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output
, 預設為None
) — Owlv2TextModel 的輸出。 - vision_model_output (
<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output
, 預設為None
) — Owlv2VisionModel 的輸出。
Owlv2ForObjectDetection 的 forward 方法會覆蓋 __call__
特殊方法。
儘管前向傳播的流程需要在此函式內定義,但之後應呼叫 `Module` 例項而不是此函式,因為前者會處理執行前處理和後處理步驟,而後者會默默地忽略它們。
示例
>>> import requests
>>> from PIL import Image
>>> import torch
>>> from transformers import Owlv2Processor, Owlv2ForObjectDetection
>>> processor = Owlv2Processor.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> 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.614 at location [341.67, 23.39, 642.32, 371.35]
Detected a photo of a cat with confidence 0.665 at location [6.75, 51.96, 326.62, 473.13]
image_guided_detection
< source >( 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.owlv2.modeling_owlv2.Owlv2ImageGuidedObjectDetectionOutput
或 tuple(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
, 可選) — 是否返回所有注意力層的注意力張量。有關詳細資訊,請參閱返回張量下的attentions
。 - output_hidden_states (
bool
, 可選) — 是否返回所有層的隱藏狀態。有關詳細資訊,請參閱返回張量下的hidden_states
。 - interpolate_pos_encoding (
bool
, 預設為False
) — 是否對預訓練的位置編碼進行插值。 - return_dict (
bool
, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。
返回
transformers.models.owlv2.modeling_owlv2.Owlv2ImageGuidedObjectDetectionOutput
或 tuple(torch.FloatTensor)
一個 transformers.models.owlv2.modeling_owlv2.Owlv2ImageGuidedObjectDetectionOutput
或一個 torch.FloatTensor
的元組(如果傳遞了 return_dict=False
或 config.return_dict=False
),根據配置(Owlv2Config)和輸入,包含各種元素。
- logits (
torch.FloatTensor
,形狀為(batch_size, num_patches, num_queries)
) — 所有查詢的分類 logits(包括無物件)。 - image_embeds (
torch.FloatTensor
,形狀為(batch_size, patch_size, patch_size, output_dim)
) — Owlv2VisionModel 的池化輸出。OWLv2 將影像表示為一組影像塊,併為每個塊計算影像嵌入。 - query_image_embeds (
torch.FloatTensor
,形狀為(batch_size, patch_size, patch_size, output_dim)
) — Owlv2VisionModel 的池化輸出。OWLv2 將影像表示為一組影像塊,併為每個塊計算影像嵌入。 - 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)
) — 所有影像塊的類別嵌入。OWLv2 將影像表示為一組影像塊,其中塊的總數為 (image_size / patch_size)**2。 - text_model_output (
<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output
, 預設為None
) — Owlv2TextModel 的輸出。 - vision_model_output (
<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output
, 預設為None
) — Owlv2VisionModel 的輸出。
示例
>>> import requests
>>> from PIL import Image
>>> import torch
>>> from transformers import AutoProcessor, Owlv2ForObjectDetection
>>> processor = AutoProcessor.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> 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")
>>> # forward pass
>>> with torch.no_grad():
... outputs = model.image_guided_detection(**inputs)
>>> 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.9, 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.938 at location [327.31, 54.94, 547.39, 268.06]
Detected similar object with confidence 0.959 at location [5.78, 360.65, 619.12, 366.39]
Detected similar object with confidence 0.902 at location [2.85, 360.01, 627.63, 380.8]
Detected similar object with confidence 0.985 at location [176.98, -29.45, 672.69, 182.83]
Detected similar object with confidence 1.0 at location [6.53, 14.35, 624.87, 470.82]
Detected similar object with confidence 0.998 at location [579.98, 29.14, 615.49, 489.05]
Detected similar object with confidence 0.985 at location [206.15, 10.53, 247.74, 466.01]
Detected similar object with confidence 0.947 at location [18.62, 429.72, 646.5, 457.72]
Detected similar object with confidence 0.996 at location [523.88, 20.69, 586.84, 483.18]
Detected similar object with confidence 0.998 at location [3.39, 360.59, 617.29, 499.21]
Detected similar object with confidence 0.969 at location [4.47, 449.05, 614.5, 474.76]
Detected similar object with confidence 0.966 at location [31.44, 463.65, 654.66, 471.07]
Detected similar object with confidence 0.924 at location [30.93, 468.07, 635.35, 475.39]