Transformers 文档

OWLv2

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始

OWLv2

PyTorch

概述

OWLv2 是由 Matthias Minderer, Alexey Gritsenko, Neil Houlsby 在 Scaling Open-Vocabulary Object Detection 中提出的。OWLv2 通过使用自训练来扩展 OWL-ViT,自训练使用现有的检测器在图像-文本对上生成伪边界框注释。这在零样本对象检测方面取得了相对于先前最先进技术的巨大提升。

论文摘要如下

开放词汇对象检测极大地受益于预训练的视觉-语言模型,但仍受限于可用的检测训练数据量。虽然可以通过使用 Web 图像-文本对作为弱监督来扩展检测训练数据,但这尚未在与图像级预训练相当的规模上完成。在这里,我们使用自训练来扩大检测数据规模,自训练使用现有的检测器在图像-文本对上生成伪边界框注释。扩展自训练的主要挑战是标签空间的选择、伪注释过滤和训练效率。我们提出了 OWLv2 模型和 OWL-ST 自训练配方,以应对这些挑战。OWLv2 在相当的训练规模(约 1000 万个示例)下,已经超越了先前最先进的开放词汇检测器的性能。然而,通过 OWL-ST,我们可以扩展到超过 10 亿个示例,从而产生更大的改进:使用 L/14 架构,OWL-ST 将 LVIS 稀有类别(模型未见过人工边界框注释)的 AP 从 31.2% 提高到 44.6%(相对改进 43%)。OWL-ST 为开放世界定位解锁了 Web 规模的训练,类似于图像分类和语言建模中所见的情况。

drawing OWLv2 高级概述。摘自 原始论文

此模型由 nielsr 贡献。原始代码可以在 这里 找到。

使用示例

OWLv2 就像它的前身 OWL-ViT 一样,是一个零样本文本条件对象检测模型。OWL-ViT 使用 CLIP 作为其多模态骨干网络,使用类似 ViT 的 Transformer 来获取视觉特征,并使用因果语言模型来获取文本特征。为了将 CLIP 用于检测,OWL-ViT 移除了视觉模型的最终 token 池化层,并将一个轻量级的分类和边界框头部连接到每个 transformer 输出 token。通过用从文本模型获得的类名嵌入替换固定的分类层权重,实现了开放词汇分类。作者首先从头开始训练 CLIP,然后使用二分图匹配损失在标准检测数据集上对带有分类和边界框头部的 CLIP 进行端到端微调。每个图像可以使用一个或多个文本查询来执行零样本文本条件对象检测。

Owlv2ImageProcessor 可以用于调整大小(或重新缩放)和标准化模型的图像,CLIPTokenizer 用于编码文本。Owlv2ProcessorOwlv2ImageProcessorCLIPTokenizer 包装到单个实例中,以同时编码文本和准备图像。以下示例展示了如何使用 Owlv2ProcessorOwlv2ForObjectDetection 执行对象检测。

>>> 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 的架构与 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: typing.Dict vision_config: typing.Dict **kwargs ) Owlv2Config

返回:

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 (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) — 输入序列中 padding token 的 id。
  • bos_token_id (int, 可选, 默认为 49406) — 输入序列中 beginning-of-sequence token 的 id。
  • eos_token_id (int, 可选, 默认为 49407) — 输入序列中 end-of-sequence 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, optional, defaults to 768) — 编码器层和池化层的维度。
  • intermediate_size (int, optional, defaults to 3072) — Transformer 编码器中“中间”层(即,前馈层)的维度。
  • num_hidden_layers (int, optional, defaults to 12) — Transformer 编码器中隐藏层的数量。
  • num_attention_heads (int, optional, defaults to 12) — Transformer 编码器中每个注意力层的注意力头的数量。
  • num_channels (int, optional, defaults to 3) — 输入图像中的通道数。
  • image_size (int, optional, defaults to 768) — 每张图片的大小(分辨率)。
  • patch_size (int, optional, defaults to 16) — 每个patch的大小(分辨率)。
  • hidden_act (str or function, optional, defaults to "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,内部用于初始化测试)。

这是用于存储 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

< >

( do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_pad: bool = True do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BILINEAR: 2> do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None **kwargs )

参数

  • do_rescale (bool, optional, defaults to True) — 是否按指定的比例 rescale_factor 重新缩放图像。可以被 preprocess 方法中的 do_rescale 重写。
  • rescale_factor (int or float, optional, defaults to 1/255) — 如果重新缩放图像,则使用的缩放因子。可以被 preprocess 方法中的 rescale_factor 重写。
  • do_pad (bool, optional, defaults to True) — 是否将图像填充为正方形,并在底部和右侧填充灰色像素。可以被 preprocess 方法中的 do_pad 重写。
  • do_resize (bool, optional, defaults to True) — 控制是否将图像的(高度,宽度)尺寸调整为指定的 size。可以被 preprocess 方法中的 do_resize 重写。
  • size (Dict[str, int] optional, defaults to {"height" -- 960, "width": 960}): 调整图像大小的目标尺寸。可以被 preprocess 方法中的 size 重写。
  • resample (PILImageResampling, optional, defaults to Resampling.BILINEAR) — 如果调整图像大小,则使用的重采样方法。可以被 preprocess 方法中的 resample 重写。
  • do_normalize (bool, optional, defaults to True) — 是否标准化图像。可以被 preprocess 方法中的 do_normalize 参数重写。
  • image_mean (float or List[float], optional, defaults to OPENAI_CLIP_MEAN) — 如果标准化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被 preprocess 方法中的 image_mean 参数重写。
  • image_std (float or List[float], optional, defaults to OPENAI_CLIP_STD) — 如果标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被 preprocess 方法中的 image_std 参数重写。

构建 Owlv2 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_pad: bool = None do_resize: bool = None size: typing.Dict[str, int] = None do_rescale: bool = None rescale_factor: float = None do_normalize: 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: 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, optional, defaults to self.do_pad) — 是否将图像填充为正方形,并在底部和右侧填充灰色像素。
  • do_resize (bool, optional, defaults to 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 (floatList[float], 可选, 默认为 self.image_mean) — 图像均值。
  • image_std (floatList[float], 可选, 默认为 self.image_std) — 图像标准差。
  • 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) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST: 图像格式为 (num_channels, height, width)。
    • "channels_last"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: Owlv2ObjectDetectionOutput threshold: float = 0.1 target_sizes: typing.Union[transformers.utils.generic.TensorType, typing.List[typing.Tuple], NoneType] = None ) List[Dict]

参数

  • outputs (Owlv2ObjectDetectionOutput) — 模型的原始输出。
  • 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)。

Owlv2ForObjectDetection 的原始输出转换为最终的边界框,格式为 (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)。如果设置,则预测的归一化边界框将重新缩放到目标尺寸。如果留空,则不会取消归一化预测。

返回:

List[Dict]

字典列表,每个字典都包含模型预测的批次中图像的分数、标签和框。所有标签都设置为 None,因为 OwlViTForObjectDetection.image_guided_detection 执行一次性物体检测。

OwlViTForObjectDetection.image_guided_detection() 的输出转换为 COCO api 期望的格式。

Owlv2Processor

class transformers.Owlv2Processor

< >

( image_processor tokenizer **kwargs )

参数

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

构建一个 Owlv2 处理器,它将 Owlv2ImageProcessorCLIPTokenizer/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.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 张量。支持通道优先和通道最后的格式。
  • 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: Owlv2ObjectDetectionOutput 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 (Owlv2ObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, optional, 默认为 0.1) — 保留对象检测预测的分数阈值。
  • target_sizes (torch.TensorList[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

< >

( outputs: Owlv2ImageGuidedObjectDetectionOutput 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 (Owlv2ImageGuidedObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, optional, 默认为 0.0) — 用于滤除预测框的最小置信度阈值。
  • nms_threshold (float, optional, 默认为 0.3) — 用于重叠框的非极大值抑制的 IoU 阈值。
  • target_sizes (torch.Tensor, optional) — 形状为 (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

< >

( config: Owlv2Config )

参数

  • config (Owvl2Config) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 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.owlv2.modeling_owlv2.Owlv2Output or tuple(torch.FloatTensor)

参数

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

返回:

transformers.models.owlv2.modeling_owlv2.Owlv2Output or tuple(torch.FloatTensor)

transformers.models.owlv2.modeling_owlv2.Owlv2Outputtorch.FloatTensor 的元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含各种元素,具体取决于配置 (<class 'transformers.models.owlv2.configuration_owlv2.Owlv2Config'>) 和输入。

  • loss (torch.FloatTensor of shape (1,), optional, returned when return_loss is True) — 图像-文本相似度的对比损失。
  • 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) — 通过将投影层应用于 Owlv2TextModel 的池化输出而获得的文本嵌入。
  • image_embeds (torch.FloatTensor of shape (batch_size, output_dim) — 通过将投影层应用于 Owlv2VisionModel 的池化输出而获得的图像嵌入。
  • text_model_output (TupleBaseModelOutputWithPooling) — Owlv2TextModel 的输出。
  • vision_model_output (BaseModelOutputWithPooling) — Owlv2VisionModel 的输出。

Owlv2Model 的 forward 方法重写了 __call__ 特殊方法。

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

< >

( 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)) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。详见 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是 input IDs?
  • attention_mask (torch.Tensor of shape (batch_size, num_max_text_queries, sequence_length), optional) — 用于避免对 padding token 索引执行注意力的掩码。掩码值在 [0, 1] 中选择:
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。详见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。详见返回张量下的 hidden_states
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通元组。

返回:

text_features (torch.FloatTensor of shape (batch_size, output_dim)

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

Owlv2Model 的 forward 方法重写了 __call__ 特殊方法。

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

示例

>>> 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

< >

( 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 of shape (batch_size, output_dim)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。详见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。详见返回张量下的 hidden_states
  • interpolate_pos_encoding (bool, optional, defaults False) — 是否插值预训练的位置编码。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通元组。

返回:

image_features (torch.FloatTensor of shape (batch_size, output_dim)

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

Owlv2Model 的 forward 方法重写了 __call__ 特殊方法。

尽管 forward 过程的配方需要在该函数中定义,但应该在之后调用 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(images=image, return_tensors="pt")
>>> image_features = model.get_image_features(**inputs)

Owlv2TextModel

class transformers.Owlv2TextModel

< >

( config: Owlv2TextConfig )

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.BaseModelOutputWithPooling or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor of shape (batch_size * num_max_text_queries, sequence_length)) — 词汇表中输入序列 tokens 的索引。索引可以使用 AutoTokenizer 获得。详见 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是 input IDs?
  • attention_mask (torch.Tensor of shape (batch_size, num_max_text_queries, sequence_length), optional) — 用于避免对 padding token 索引执行注意力的掩码。掩码值在 [0, 1] 中选择:
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。详见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。详见返回张量下的 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.owlv2.configuration_owlv2.Owlv2TextConfig'>) 和输入的各种元素。

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

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

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

class transformers.Owlv2VisionModel

< >

( config: Owlv2VisionConfig )

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.owlv2.configuration_owlv2.Owlv2VisionConfig'>) 和输入的各种元素。

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

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

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

class transformers.Owlv2ForObjectDetection

< >

( config: Owlv2Config )

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.owlv2.modeling_owlv2.Owlv2ObjectDetectionOutputtuple(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), 可选) — 掩码,以避免对 padding token 索引执行注意力机制。Mask values selected in [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.owlv2.modeling_owlv2.Owlv2ObjectDetectionOutputtuple(torch.FloatTensor)

一个 transformers.models.owlv2.modeling_owlv2.Owlv2ObjectDetectionOutput 或一个 torch.FloatTensor 元组(如果传递了 return_dict=False 或当 config.return_dict=False 时),包含取决于配置 (<class 'transformers.models.owlv2.configuration_owlv2.Owlv2Config'>) 和输入的各种元素。

  • loss (torch.FloatTensor,形状为 (1,), 可选, 当提供 labels 时返回)) — 总损失,作为类别预测的负对数似然(交叉熵)损失和边界框损失的线性组合。后者定义为 L1 损失和广义尺度不变 IoU 损失的线性组合。
  • loss_dict (Dict, 可选) — 包含各个损失的字典。用于记录日志时很有用。
  • logits (torch.FloatTensor,形状为 (batch_size, num_patches, num_queries)) — 所有 queries 的分类 logits(包括无对象)。
  • objectness_logits (torch.FloatTensor,形状为 (batch_size, num_patches, 1)) — 所有图像 patches 的对象性 logits。OWL-ViT 将图像表示为一组图像 patches,其中 patches 总数为 (image_size / patch_size)**2。
  • pred_boxes (torch.FloatTensor,形状为 (batch_size, num_patches, 4)) — 所有 queries 的归一化框坐标,表示为 (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) — 通过将投影层应用于 Owlv2TextModel 的 pooled 输出获得的文本嵌入。
  • image_embeds (torch.FloatTensor,形状为 (batch_size, patch_size, patch_size, output_dim) — Owlv2VisionModel 的 pooled 输出。OWLv2 将图像表示为一组图像 patches,并计算每个 patch 的图像嵌入。
  • class_embeds (torch.FloatTensor,形状为 (batch_size, num_patches, hidden_size)) — 所有图像 patches 的类别嵌入。OWLv2 将图像表示为一组图像 patches,其中 patches 总数为 (image_size / patch_size)**2。
  • text_model_output (TupleBaseModelOutputWithPooling) — Owlv2TextModel 的输出。
  • vision_model_output (BaseModelOutputWithPooling) — Owlv2VisionModel 的输出。

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

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

< >

( 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.Owlv2ImageGuidedObjectDetectionOutputtuple(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, optional) — 是否返回所有层的隐藏状态。 详见返回张量下的 hidden_states 以了解更多细节。
  • interpolate_pos_encoding (bool, optional, defaults False) — 是否插值预训练的位置编码。
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 对象而不是一个普通元组。

返回:

transformers.models.owlv2.modeling_owlv2.Owlv2ImageGuidedObjectDetectionOutput or tuple(torch.FloatTensor)

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

  • logits (torch.FloatTensor,形状为 (batch_size, num_patches, num_queries)) — 所有 queries 的分类 logits(包括无对象)。
  • target_pred_boxes (torch.FloatTensor of shape (batch_size, num_patches, 4)) — 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。 这些值在 [0, 1] 范围内归一化,相对于批次中每个目标图像的大小(忽略可能的填充)。 您可以使用 post_process_object_detection() 来检索未归一化的边界框。
  • query_pred_boxes (torch.FloatTensor of shape (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) — Owlv2VisionModel 的 pooled 输出。OWLv2 将图像表示为一组图像 patches,并计算每个 patch 的图像嵌入。
  • query_image_embeds (torch.FloatTensor of shape (batch_size, patch_size, patch_size, output_dim) — Owlv2VisionModel 的池化输出。 OWLv2 将图像表示为一组图像块,并计算每个图像块的图像嵌入。
  • class_embeds (torch.FloatTensor,形状为 (batch_size, num_patches, hidden_size)) — 所有图像 patches 的类别嵌入。OWLv2 将图像表示为一组图像 patches,其中 patches 总数为 (image_size / patch_size)**2。
  • text_model_output (TupleBaseModelOutputWithPooling) — Owlv2TextModel 的输出。
  • vision_model_output (BaseModelOutputWithPooling) — Owlv2VisionModel 的输出。

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

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

示例

>>> 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]
< > 在 GitHub 上更新