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