Transformers 文档

OWL-ViT

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

OWL-ViT

PyTorch

概述

OWL-ViT(Open-World Localization 视觉 Transformer 的缩写)由 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 在 Simple Open-Vocabulary Object Detection with Vision Transformers 中提出。OWL-ViT 是一个在各种(图像,文本)对上训练的开放词汇目标检测网络。它可用于使用一个或多个文本查询来查询图像,以搜索和检测文本中描述的目标对象。

论文摘要如下:

将简单的架构与大规模预训练相结合,极大地改进了图像分类。对于目标检测,预训练和缩放方法不太成熟,尤其是在长尾和开放词汇设置中,训练数据相对稀缺。在本文中,我们为将图像-文本模型迁移到开放词汇目标检测提出了一个强有力的方案。我们使用标准的视觉 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 进行零样本和单样本(图像引导)目标检测的演示 notebook 可以在这里找到。

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: typing.Dict vision_config: typing.Dict **kwargs ) OwlViTConfig

返回

OwlViTConfig

配置对象的实例

从 owlvit 文本模型配置和 owlvit 视觉模型配置实例化一个 OwlViTConfig(或派生类)。

OwlViTTextConfig

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, optional, 默认为 49408) — OWL-ViT 文本模型的词汇表大小。定义了在调用 OwlViTTextModel 时传递的 inputs_ids 可以表示的不同 tokens 的数量。
  • hidden_size (int, optional, 默认为 512) — 编码器层和池化器层的维度。
  • intermediate_size (int, optional, 默认为 2048) — Transformer 编码器中“中间” (即,前馈) 层的维度。
  • num_hidden_layers (int, optional, 默认为 12) — Transformer 编码器中隐藏层的数量。
  • num_attention_heads (int, optional, 默认为 8) — Transformer 编码器中每个注意力层的注意力头的数量。
  • max_position_embeddings (int, optional, 默认为 16) — 模型可能使用的最大序列长度。通常将其设置为较大的值以防万一 (例如,512 或 1024 或 2048)。
  • hidden_act (strfunction, optional, 默认为 "quick_gelu") — 编码器和池化器中的非线性激活函数 (函数或字符串)。 如果是字符串,则支持 "gelu", "relu", "selu", "gelu_new""quick_gelu"
  • layer_norm_eps (float, optional, 默认为 1e-05) — 层归一化层使用的 epsilon 值。
  • attention_dropout (float, optional, 默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • initializer_factor (float, optional, 默认为 1.0) — 用于初始化所有权重矩阵的因子 (应保持为 1,在内部用于初始化测试)。
  • pad_token_id (int, optional, 默认为 0) — 输入序列中填充 token 的 id。
  • bos_token_id (int, optional, 默认为 49406) — 输入序列中 sequence-起始 token 的 id。
  • eos_token_id (int, optional, 默认为 49407) — 输入序列中 sequence-结束 token 的 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

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, optional, 默认为 768) — 编码器层和池化器层的维度。
  • intermediate_size (int, optional, 默认为 3072) — Transformer 编码器中“中间” (即,前馈) 层的维度。
  • num_hidden_layers (int, optional, 默认为 12) — Transformer 编码器中隐藏层的数量。
  • num_attention_heads (int, optional, 默认为 12) — Transformer 编码器中每个注意力层的注意力头的数量。
  • num_channels (int, optional, 默认为 3) — 输入图像中的通道数。
  • image_size (int, optional, 默认为 768) — 每个图像的大小(分辨率)。
  • patch_size (int, optional, 默认为 32) — 每个 patch 的大小(分辨率)。
  • hidden_act (strfunction, 可选, 默认为 "quick_gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,则支持 "gelu""relu""selu""gelu_new""quick_gelu"
  • layer_norm_eps (float, 可选, 默认为 1e-05) — 层归一化层使用的 epsilon 值。
  • attention_dropout (float, 可选, 默认为 0.0) — attention 概率的 dropout 比率。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated\_normal\_initializer 的标准差。
  • initializer_factor (float, 可选, 默认为 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, 可选, 默认为 True) — 是否将输入图像的较短边调整为特定 size 大小。
  • size (Dict[str, int], 可选, 默认为 {“height” — 768, “width”: 768}): 用于调整图像大小的尺寸。 仅当 do_resize 设置为 True 时才生效。 如果 size 是类似 (h, w) 的序列,则输出大小将与此匹配。 如果 size 是一个整数,则图像将被调整为 (size, size) 大小。
  • resample (int, 可选, 默认为 Resampling.BICUBIC) — 可选的重采样过滤器。 可以是 PIL.Image.Resampling.NEAREST, PIL.Image.Resampling.BOX, PIL.Image.Resampling.BILINEAR, PIL.Image.Resampling.HAMMING, PIL.Image.Resampling.BICUBICPIL.Image.Resampling.LANCZOS 之一。 仅当 do_resize 设置为 True 时才生效。
  • do_center_crop (bool, 可选, 默认为 False) — 是否在中心裁剪输入图像。 如果输入尺寸在任何边缘都小于 crop_size,则图像将用 0 填充,然后进行中心裁剪。
  • crop_size (int, 可选, 默认为 {“height” — 768, “width”: 768}): 用于中心裁剪图像的尺寸。 仅当 do_center_crop 设置为 True 时才生效。
  • do_rescale (bool, 可选, 默认为 True) — 是否按一定因子缩放输入图像。
  • rescale_factor (float, 可选, 默认为 1/255) — 用于缩放图像的因子。 仅当 do_rescale 设置为 True 时才生效。
  • do_normalize (bool, 可选, 默认为 True) — 是否使用 image_meanimage_std 对输入进行归一化。 应用中心裁剪时所需的输出大小。 仅当 do_center_crop 设置为 True 时才生效。
  • image_mean (List[int], 可选, 默认为 [0.48145466, 0.4578275, 0.40821073]) — 每个通道的均值序列,用于归一化图像。
  • image_std (List[int], 可选, 默认为 [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[typing.Dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[typing.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, 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, 可选, 默认为 self.do_resize) — 是否调整输入大小。 如果为 True,则会将输入调整为 size 指定的大小。
  • size (Dict[str, int], 可选, 默认为 self.size) — 要将输入调整为的大小。 仅当 do_resize 设置为 True 时才生效。
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 调整输入大小时要使用的重采样过滤器。 仅当 do_resize 设置为 True 时才生效。
  • do_center_crop (bool, 可选, 默认为 self.do_center_crop) — 是否中心裁剪输入。 如果为 True,则会将输入中心裁剪为 crop_size 指定的大小。
  • crop_size (Dict[str, int]可选,默认为 self.crop_size) — 要将输入中心裁剪到的尺寸。仅当 do_center_crop 设置为 True 时才生效。
  • do_rescale (bool可选,默认为 self.do_rescale) — 是否对输入进行重新缩放。如果为 True,将通过除以 rescale_factor 来重新缩放输入。
  • rescale_factor (float可选,默认为 self.rescale_factor) — 用于重新缩放输入的因子。仅当 do_rescale 设置为 True 时才生效。
  • do_normalize (bool可选,默认为 self.do_normalize) — 是否对输入进行归一化。如果为 True,将通过减去 image_mean 并除以 image_std 来归一化输入。
  • image_mean (Union[float, List[float]]可选,默认为 self.image_mean) — 归一化时从输入中减去的均值。仅当 do_normalize 设置为 True 时才生效。
  • image_std (Union[float, List[float]]可选,默认为 self.image_std) — 归一化时用于除以输入的标准差。仅当 do_normalize 设置为 True 时才生效。
  • return_tensors (strTensorType可选) — 要返回的张量类型。可以是以下之一:
    • Unset:返回 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 (ChannelDimensionstr可选,默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • ChannelDimension.FIRST:(num_channels, height, width) 格式的图像。
    • ChannelDimension.LAST:(height, width, num_channels) 格式的图像。
    • Unset:默认为输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "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

< >

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

参数

  • outputs (OwlViTObjectDetectionOutput) — 模型的原始输出。
  • threshold (float可选,默认为 0.1) — 保持物体检测预测的分数阈值。
  • target_sizes (torch.TensorList[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) 格式的图像边界框。

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可选,默认为 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 期望的格式。

OwlViTProcessor

class transformers.OwlViTProcessor

< >

( image_processor = None tokenizer = None **kwargs )

参数

  • image_processor (OwlViTImageProcessor可选) — 图像处理器是必需的输入。
  • tokenizer ([CLIPTokenizer, CLIPTokenizerFast],可选) — 分词器是必需的输入。

构建一个 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, typing.List[str], typing.List[typing.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 (strTensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'tf':返回 TensorFlow tf.constant 对象。
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
    • 'jax':返回 JAX jnp.ndarray 对象。

返回

BatchFeature

一个 BatchFeature,包含以下字段

  • input_ids — 要馈送到模型的 token id 列表。当 text 不为 None 时返回。
  • attention_mask — 索引列表,用于指定模型应关注哪些 token (当 return_attention_mask=True 或如果 “attention_mask”self.model_input_names 中且 text 不为 None 时返回)。
  • pixel_values — 要馈送到模型的像素值。当 images 不为 None 时返回。
  • query_pixel_values — 要馈送到模型的查询图像的像素值。当 query_images 不为 None 时返回。

准备模型的一个或多个文本和图像的主要方法。如果 text 不为 None,此方法将 textkwargs 参数转发到 CLIPTokenizerFast 的 call() 以编码:文本。为了准备图像,如果 images 不为 None,此方法将 imageskwrags 参数转发到 CLIPImageProcessor 的 call()。有关更多信息,请参阅上述两种方法的文档字符串。

post_process_grounded_object_detection

< >

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

参数

  • outputs (OwlViTObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选, 默认为 0.1) — 用于保留物体检测预测的分数阈值。
  • target_sizes (torch.TensorList[Tuple[int, int]], 可选) — 形状为 (batch_size, 2) 的张量或元组列表 (Tuple[int, int]),其中包含批次中每个图像的目标大小 (height, width)。如果未设置,则不会调整预测大小。
  • 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”:图像上每个预测边界框的文本标签。

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, typing.List[typing.Tuple], NoneType] = 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]

字典列表,每个字典包含以下键

  • “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() 方法以加载模型权重。

此模型继承自 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.OwlViTOutputtuple(torch.FloatTensor)

参数

  • input_ids (形状为 (batch_size, sequence_length)torch.LongTensor) — 词汇表中输入序列 token 的索引。索引可以使用 AutoTokenizer 获得。有关详细信息,请参见 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是输入 ID?
  • attention_mask (形状为 (batch_size, sequence_length)torch.Tensor, 可选) — 掩码,用于避免对 padding token 索引执行 attention。掩码值在 [0, 1] 中选择:
  • pixel_values (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 像素值。
  • return_loss (bool, 可选) — 是否返回对比损失。
  • output_attentions (bool, 可选) — 是否返回所有 attention 层的 attentions 张量。 有关更多详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 详见返回张量下的 hidden_states
  • interpolate_pos_encoding (bool, optional, defaults False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯粹的元组。

返回

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

一个 transformers.models.owlvit.modeling_owlvit.OwlViTOutputtorch.FloatTensor 元组 (如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (<class 'transformers.models.owlvit.configuration_owlvit.OwlViTConfig'>) 和输入。

  • loss (形状为 (1,)torch.FloatTensor可选,当 return_lossTrue 时返回) — 图像-文本相似度的对比损失。
  • logits_per_image (形状为 (image_batch_size, text_batch_size)torch.FloatTensor) — image_embedstext_embeds 之间缩放的点积得分。 这表示图像-文本相似度得分。
  • logits_per_text (形状为 (text_batch_size, image_batch_size)torch.FloatTensor) — text_embedsimage_embeds 之间缩放的点积得分。 这表示文本-图像相似度得分。
  • text_embeds (形状为 (batch_size * num_max_text_queries, output_dim) 的 torch.FloatTensor) — 通过将投影层应用于 OwlViTTextModel 的池化输出而获得的文本嵌入。
  • image_embeds (形状为 (batch_size, output_dim) 的 torch.FloatTensor) — 通过将投影层应用于 OwlViTVisionModel 的池化输出而获得的图像嵌入。
  • text_model_output (TupleBaseModelOutputWithPooling) — OwlViTTextModel 的输出。
  • vision_model_output (BaseModelOutputWithPooling) — OwlViTVisionModel 的输出。

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

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 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 (形状为 (batch_size, output_dim) 的 torch.FloatTensor)

参数

  • input_ids (形状为 (batch_size * num_max_text_queries, sequence_length)torch.LongTensor) — 词汇表中输入序列 tokens 的索引。 索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是输入 ID?
  • attention_mask (形状为 (batch_size, num_max_text_queries, sequence_length)torch.Tensor可选) — 用于避免在 padding token 索引上执行 attention 的掩码。 Mask 值在 [0, 1] 中选择:
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attentions 张量。 详见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 详见返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯粹的元组。

返回

text_features (形状为 (batch_size, output_dim) 的 torch.FloatTensor)

通过将投影层应用于 OwlViTTextModel 的池化输出而获得的文本嵌入。

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

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 Module 实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> 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 (形状为 (batch_size, output_dim) 的 torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, height, width)torch.FloatTensor) — 像素值。
  • output_attentions (bool, optional) — 是否返回所有 attention 层的 attentions 张量。 详见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。 详见返回张量下的 hidden_states
  • interpolate_pos_encoding (bool, optional, defaults False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是纯粹的元组。

返回

image_features (形状为 (batch_size, output_dim) 的 torch.FloatTensor)

通过将投影层应用于 OwlViTVisionModel 的池化输出而获得的图像嵌入。

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

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 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(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 (形状为 (batch_size * num_max_text_queries, sequence_length)torch.LongTensor) — 词汇表中输入序列 tokens 的索引。 索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是输入 ID?
  • attention_mask (形状为 (batch_size, num_max_text_queries, sequence_length)torch.Tensor可选) — 用于避免在 padding token 索引上执行 attention 的掩码。 Mask 值在 [0, 1] 中选择:
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 更多细节请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 更多细节请参阅返回张量下的 hidden_states
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是纯元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 torch.FloatTensor 元组 (如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (<class 'transformers.models.owlvit.configuration_owlvit.OwlViTTextConfig'>) 和输入。

  • last_hidden_state (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层的输出端的隐藏状态序列。

  • pooler_output (torch.FloatTensor,形状为 (batch_size, hidden_size)) — 序列的第一个 token (分类 token) 的最后一层隐藏状态,在通过用于辅助预训练任务的层进一步处理之后。 例如,对于 BERT 系列模型,这将返回通过线性层和 tanh 激活函数处理后的分类 token。 线性层权重从预训练期间的下一句预测(分类)目标中训练而来。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

OwlViTTextModel forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 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, height, width)) — 像素值。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。 更多细节请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。 更多细节请参阅返回张量下的 hidden_states
  • interpolate_pos_encoding (bool, 可选, 默认为 False) — 是否插值预训练的位置编码。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是纯元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 torch.FloatTensor 元组 (如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (<class 'transformers.models.owlvit.configuration_owlvit.OwlViTVisionConfig'>) 和输入。

  • last_hidden_state (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)) — 模型最后一层的输出端的隐藏状态序列。

  • pooler_output (torch.FloatTensor,形状为 (batch_size, hidden_size)) — 序列的第一个 token (分类 token) 的最后一层隐藏状态,在通过用于辅助预训练任务的层进一步处理之后。 例如,对于 BERT 系列模型,这将返回通过线性层和 tanh 激活函数处理后的分类 token。 线性层权重从预训练期间的下一句预测(分类)目标中训练而来。

  • 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 后的注意力权重,用于计算自注意力头中的加权平均值。

OwlViTVisionModel forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 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)

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 像素值。
  • input_ids (torch.LongTensor,形状为 (batch_size * num_max_text_queries, sequence_length), 可选) — 词汇表中输入序列 tokens 的索引。 索引可以使用 AutoTokenizer 获得。 有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是输入 IDs?
  • attention_mask (torch.Tensor,形状为 (batch_size, num_max_text_queries, sequence_length), 可选) — Mask,用于避免在 padding token 索引上执行注意力机制。 Mask 值在 [0, 1] 中选择:
  • output_hidden_states (bool, 可选) — 是否返回最后的隐藏状态。 更多细节请参阅返回张量下的 text_model_last_hidden_statevision_model_last_hidden_state
  • interpolate_pos_encoding (bool, 可选, 默认为 False) — 是否插值预训练的位置编码。
  • return_dict (bool, 可选) — 是否返回 ModelOutput 而不是纯元组。

返回

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

一个 transformers.models.owlvit.modeling_owlvit.OwlViTObjectDetectionOutput 或一个 torch.FloatTensor 元组 (如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (<class 'transformers.models.owlvit.configuration_owlvit.OwlViTConfig'>) 和输入。

  • loss (torch.FloatTensor,形状为 (1,), 可选, 当提供 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] 范围内标准化,相对于 batch 中每个单独图像的大小(忽略可能的 padding)。 您可以使用 post_process_object_detection() 来检索未标准化的边界框。
  • text_embeds (torch.FloatTensor,形状为 (batch_size, num_max_text_queries, output_dim) — 通过将投影层应用于 OwlViTTextModel 的 pooled 输出获得的文本嵌入。
  • image_embeds (torch.FloatTensor,形状为 (batch_size, patch_size, patch_size, output_dim) — OwlViTVisionModel 的 Pooled 输出。 OWL-ViT 将图像表示为一组图像 patches,并为每个 patch 计算图像嵌入。
  • class_embeds (torch.FloatTensor,形状为 (batch_size, num_patches, hidden_size)) — 所有图像 patches 的类别嵌入。 OWL-ViT 将图像表示为一组图像 patches,其中 patches 的总数为 (image_size / patch_size)**2。
  • text_model_output (TupleBaseModelOutputWithPooling) — OwlViTTextModel 的输出。
  • vision_model_output (BaseModelOutputWithPooling) — OwlViTVisionModel 的输出。

OwlViTForObjectDetection forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 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, height, width)) — 像素值。
  • 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.owlvit.modeling_owlvit.OwlViTImageGuidedObjectDetectionOutputtuple(torch.FloatTensor)

一个 transformers.models.owlvit.modeling_owlvit.OwlViTImageGuidedObjectDetectionOutputtorch.FloatTensor 元组 (如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (<class 'transformers.models.owlvit.configuration_owlvit.OwlViTConfig'>) 和输入。

  • logits (torch.FloatTensor,形状为 (batch_size, num_patches, num_queries)) — 所有查询的分类 logits(包括无对象)。
  • 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() 来检索非归一化边界框。
  • image_embeds (torch.FloatTensor,形状为 (batch_size, patch_size, patch_size, output_dim) — OwlViTVisionModel 的 Pooled 输出。 OWL-ViT 将图像表示为一组图像 patches,并为每个 patch 计算图像嵌入。
  • query_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)) — 所有图像 patches 的类别嵌入。 OWL-ViT 将图像表示为一组图像 patches,其中 patches 的总数为 (image_size / patch_size)**2。
  • text_model_output (TupleBaseModelOutputWithPooling) — OwlViTTextModel 的输出。
  • vision_model_output (BaseModelOutputWithPooling) — OwlViTVisionModel 的输出。

OwlViTForObjectDetection forward 方法,覆盖了 __call__ 特殊方法。

尽管 forward 传递的配方需要在该函数中定义,但应在此之后调用 Module 实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

示例

>>> 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 上更新