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,该方法利用现有检测器在图文对上生成伪框标注。这使得其在零样本目标检测方面比之前的 SOTA 模型取得了巨大进步。

论文摘要如下:

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

drawing OWLv2 概览图。引自原始论文

该模型由 nielsr 贡献。原始代码可在此处找到。

用法示例

OWLv2 和其前身 OWL-ViT 一样,是一个零样本文本条件的目标检测模型。OWL-ViT 使用 CLIP 作为其多模态主干,通过一个类 ViT 的 Transformer 获取视觉特征,通过一个因果语言模型获取文本特征。为了将 CLIP 用于检测,OWL-ViT 移除了视觉模型的最终 token 池化层,并在每个 Transformer 输出 token 上附加了一个轻量级的分类和框头。通过将固定的分类层权重替换为从文本模型获得的类名嵌入,实现了开放词汇分类。作者首先从头开始训练 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: dict vision_config: 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) — 输入序列中填充 token 的 id。
  • bos_token_id (int, 可选, 默认为 49406) — 输入序列中序列开始 token 的 id。
  • eos_token_id (int, 可选, 默认为 49407) — 输入序列中序列结束 token 的 id。

这是用于存储 Owlv2TextModel 配置的配置类。它用于根据指定的参数实例化一个 Owlv2 文本编码器,定义模型架构。使用默认值实例化配置将产生与 Owlv2 google/owlv2-base-patch16 架构类似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。

示例

>>> from transformers import Owlv2TextConfig, Owlv2TextModel

>>> # Initializing a Owlv2TextModel with google/owlv2-base-patch16 style configuration
>>> configuration = Owlv2TextConfig()

>>> # Initializing a Owlv2TextConfig from the google/owlv2-base-patch16 style configuration
>>> model = Owlv2TextModel(configuration)

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

Owlv2VisionConfig

class transformers.Owlv2VisionConfig

< >

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

参数

  • hidden_size (int, 可选, 默认为 768) — 编码器层和池化层的维度。
  • intermediate_size (int, 可选, 默认为 3072) — Transformer 编码器中“中间”(即前馈)层的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数量。
  • num_channels (int, 可选, 默认为 3) — 输入图像中的通道数。
  • image_size (int, 可选, 默认为 768) — 每个图像的大小(分辨率)。
  • patch_size (int, 可选, 默认为 16) — 每个补丁(patch)的大小(分辨率)。
  • hidden_act (str or function, 可选, 默认为 "quick_gelu") — 编码器和池化器中的非线性激活函数(函数或字符串)。如果为字符串,支持 "gelu""relu""selu""gelu_new""quick_gelu"
  • layer_norm_eps (float, 可选, 默认为 1e-05) — 层归一化层使用的 epsilon 值。
  • attention_dropout (float, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • initializer_factor (float, 可选, 默认为 1.0) — 用于初始化所有权重矩阵的因子(应保持为 1,内部用于初始化测试)。

这是用于存储 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.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None **kwargs )

参数

  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的比例 `rescale_factor` 来缩放图像。可以在 `preprocess` 方法中通过 `do_rescale` 覆盖。
  • rescale_factor (int or float, 可选, 默认为 1/255) — 如果缩放图像,则使用的比例因子。可以在 `preprocess` 方法中通过 `rescale_factor` 覆盖。
  • do_pad (bool, 可选, 默认为 True) — 是否在底部和右侧用灰色像素将图像填充为正方形。可以在 `preprocess` 方法中通过 `do_pad` 覆盖。
  • do_resize (bool, 可选, 默认为 True) — 控制是否将图像的(高度,宽度)尺寸调整为指定的 `size`。可以在 `preprocess` 方法中通过 `do_resize` 覆盖。
  • size (dict[str, int], 可选, 默认为 {"height": 960, "width": 960}):要将图像调整到的大小。可以在 `preprocess` 方法中通过 `size` 覆盖。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BILINEAR) — 如果调整图像大小,则使用的重采样方法。可以在 `preprocess` 方法中通过 `resample` 覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可以在 `preprocess` 方法中通过 `do_normalize` 参数覆盖。
  • image_mean (float or list[float], 可选, 默认为 OPENAI_CLIP_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或长度等于图像通道数的浮点数列表。可以在 `preprocess` 方法中通过 `image_mean` 参数覆盖。
  • image_std (float or list[float], 可选, 默认为 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: typing.Optional[bool] = None do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • images (ImageInput) — 待预处理的图像。需要单个或一批像素值在 0 到 255 范围内的图像。如果传入像素值在 0 到 1 之间的图像,请设置 `do_rescale=False`。
  • do_pad (bool, 可选, 默认为 self.do_pad) — 是否在底部和右侧用灰色像素将图像填充为正方形。
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 self.size) — 要将图像调整到的大小。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 `do_rescale` 设置为 `True`,则用于缩放图像的比例因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化。
  • image_mean (float or list[float], 可选, 默认为 self.image_mean) — 图像均值。
  • image_std (float or list[float], 可选, 默认为 self.image_std) — 图像标准差。
  • return_tensors (str or TensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • 未设置:返回 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, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimension or str, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "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, list[tuple], NoneType] = None ) list[Dict]

参数

  • outputs (Owlv2ObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选, 默认为 0.1) — 用于保留目标检测预测结果的分数阈值。
  • target_sizes (torch.Tensor or list[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)。如果设置,预测的归一化边界框将被重新缩放到目标尺寸。如果留空为 None,预测结果将不会被反归一化。

返回

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, list[str], list[list[str]]] = None *args audio = None videos = None **kwargs: typing_extensions.Unpack[transformers.models.owlv2.processing_owlv2.Owlv2ProcessorKwargs] ) BatchFeature

参数

  • images (PIL.Image.Image, np.ndarray, torch.Tensor, list[PIL.Image.Image], list[np.ndarray], —
  • list[torch.Tensor]) — 要准备的图像或图像批次。每个图像可以是 PIL 图像、NumPy 数组或 PyTorch 张量。支持 channels-first 和 channels-last 两种格式。
  • text (str, list[str], list[list[str]]) — 要编码的序列或序列批次。每个序列可以是一个字符串或一个字符串列表(预分词的字符串)。如果序列以字符串列表(预分词)形式提供,您必须设置 `is_split_into_words=True`(以消除与序列批次的歧义)。
  • query_images (PIL.Image.Image, np.ndarray, torch.Tensor, list[PIL.Image.Image], list[np.ndarray], list[torch.Tensor]) — 要准备的查询图像,每个要查询的目标图像需要一个查询图像。每个图像可以是 PIL 图像、NumPy 数组或 PyTorch 张量。对于 NumPy 数组/PyTorch 张量,每个图像的形状应为 (C, H, W),其中 C 是通道数,H 和 W 是图像的高度和宽度。
  • return_tensors (str or TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值包括:
    • 'tf': 返回 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` 时返回。

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

post_process_grounded_object_detection

< >

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

参数

  • outputs (Owlv2ObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选, 默认为 0.1) — 用于保留目标检测预测的分数阈值。
  • target_sizes (torch.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, list[tuple], NoneType] = None ) list[Dict]

参数

  • outputs (Owlv2ImageGuidedObjectDetectionOutput) — 模型的原始输出。
  • threshold (float, 可选, 默认为 0.0) — 用于过滤预测框的最低置信度阈值。
  • nms_threshold (float, 可选, 默认为 0.3) — 用于非极大值抑制重叠框的 IoU 阈值。
  • target_sizes (torch.Tensor, 可选) — 形状为 (batch_size, 2) 的张量,其中每个条目是批次中相应图像的 (高度, 宽度)。如果设置,预测的归一化边界框将重新缩放到目标尺寸。如果保持为 None,预测将不会被反归一化。

返回

list[Dict]

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

  • “scores”:图像上每个预测框的置信度分数。
  • “boxes”:图像边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
  • “labels”:设置为 None

Owlv2ForObjectDetection.image_guided_detection() 的输出转换为 COCO API 所期望的格式。

Owlv2Model

class transformers.Owlv2Model

< >

( config: Owlv2Config )

参数

  • config (Owlv2Config) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。

基础的 Owlv2 模型,输出原始的隐藏状态,顶部没有任何特定的头。

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

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length), 可选) — 词汇表中输入序列标记的索引。默认情况下,填充将被忽略。

    索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size), 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获得。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length), 可选) — 用于避免对填充标记索引执行注意力操作的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩码
    • 0 表示标记被掩码

    什么是注意力掩码?

  • return_loss (bool, 可选) — 是否返回对比损失。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 `attentions`。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 `hidden_states`。
  • interpolate_pos_encoding (bool, 默认为 False) — 是否对预训练的位置编码进行插值。
  • return_base_image_embeds (bool, 可选) — 是否返回基础图像嵌入。
  • return_dict (bool, 可选) — 是返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.models.owlv2.modeling_owlv2.Owlv2Outputtuple(torch.FloatTensor)

一个 transformers.models.owlv2.modeling_owlv2.Owlv2Output 或一个 `torch.FloatTensor` 的元组(如果传递 `return_dict=False` 或当 `config.return_dict=False` 时),根据配置 (Owlv2Config) 和输入包含不同的元素。

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

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

尽管前向传播的流程需要在此函数内定义,但之后应调用 `Module` 实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会默默地忽略它们。

示例

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

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

get_text_features

< >

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

参数

  • input_ids (torch.LongTensor,形状为 (batch_size * num_max_text_queries, sequence_length)) — 词汇表中输入序列标记的索引。索引可以使用 AutoTokenizer 获得。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是输入 ID?
  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length), 可选) — 用于避免对填充标记索引执行注意力操作的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩码
    • 0 表示标记被掩码

    什么是注意力掩码?

  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 `attentions`。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 `hidden_states`。
  • return_dict (bool, 可选) — 是返回一个 ModelOutput 而不是一个普通的元组。

返回

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

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

示例

>>> from transformers import AutoProcessor, Owlv2Model

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

get_image_features

< >

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

参数

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size), 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获得。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 `attentions`。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 `hidden_states`。
  • interpolate_pos_encoding (bool, 默认为 False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool, 可选) — 是返回一个 ModelOutput 而不是一个普通的元组。

返回

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

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

示例

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

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

Owlv2TextModel

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.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), 可选) — 用于避免对填充标记索引执行注意力操作的掩码。掩码值在 [0, 1] 中选择:

    • 1 表示标记未被掩码
    • 0 表示标记被掩码

    什么是注意力掩码?

  • 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` 时),根据配置 (Owlv2Config) 和输入包含不同的元素。

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

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

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 `output_hidden_states=True` 或当 `config.output_hidden_states=True` 时返回) — `torch.FloatTensor` 的元组(如果模型有嵌入层,则一个用于嵌入层的输出,+ 每个层的一个输出),形状为 `(batch_size, sequence_length, hidden_size)`。

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 `output_attentions=True` 或当 `config.output_attentions=True` 时返回) — `torch.FloatTensor` 的元组(每层一个),形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

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

尽管前向传播的流程需要在此函数内定义,但之后应调用 `Module` 实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会默默地忽略它们。

示例

>>> from transformers import AutoProcessor, Owlv2TextModel

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

Owlv2VisionModel

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, image_size, image_size), 可选) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获得。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 `attentions`。
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 `hidden_states`。
  • interpolate_pos_encoding (bool, 默认为 False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingtuple(torch.FloatTensor)

一个 transformers.modeling_outputs.BaseModelOutputWithPooling 或一个 `torch.FloatTensor` 的元组(如果传递 `return_dict=False` 或当 `config.return_dict=False` 时),根据配置 (Owlv2Config) 和输入包含不同的元素。

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

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

  • hidden_states (tuple(torch.FloatTensor), 可选, 当传递 `output_hidden_states=True` 或当 `config.output_hidden_states=True` 时返回) — `torch.FloatTensor` 的元组(如果模型有嵌入层,则一个用于嵌入层的输出,+ 每个层的一个输出),形状为 `(batch_size, sequence_length, hidden_size)`。

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple(torch.FloatTensor), 可选, 当传递 `output_attentions=True` 或当 `config.output_attentions=True` 时返回) — `torch.FloatTensor` 的元组(每层一个),形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

Owlv2VisionModel 的 forward 方法会覆盖 __call__ 特殊方法。

尽管前向传播的流程需要在此函数内定义,但之后应调用 `Module` 实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会默默地忽略它们。

示例

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

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

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

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

Owlv2ForObjectDetection

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)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size * num_max_text_queries, sequence_length), 可选) — 词汇表中输入序列标记的索引。可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()什么是输入 ID?
  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。可以使用 {image_processor_class} 获取像素值。有关详细信息,请参阅 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 处理图像)。
  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length), 可选) — 用于避免在填充标记索引上执行注意力操作的掩码。掩码值在 [0, 1] 中选择:

    • 对于未被屏蔽的标记为 1,
    • 对于被屏蔽的标记为 0。

    什么是注意力掩码?

  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回最后一个隐藏状态。有关详细信息,请参阅返回张量下的 text_model_last_hidden_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=Falseconfig.return_dict=False),根据配置(Owlv2Config)和输入,包含各种元素。

  • loss (torch.FloatTensor,形状为 (1,), 可选, 当提供 labels 时返回) — 总损失,是用于类别预测的负对数似然(交叉熵)和边界框损失的线性组合。后者定义为 L1 损失和广义尺度不变 IoU 损失的线性组合。
  • loss_dict (Dict, 可选) — 包含各个损失的字典。用于日志记录。
  • logits (torch.FloatTensor,形状为 (batch_size, num_patches, num_queries)) — 所有查询的分类 logits(包括无对象)。
  • objectness_logits (torch.FloatTensor,形状为 (batch_size, num_patches, 1)) — 所有图像块的对象性 logits。OWL-ViT 将图像表示为一组图像块,其中块的总数为 (image_size / patch_size)**2。
  • pred_boxes (torch.FloatTensor,形状为 (batch_size, num_patches, 4)) — 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每个单独图像的大小(不考虑可能的填充)。你可以使用 post_process_object_detection() 来检索未归一化的边界框。
  • text_embeds (torch.FloatTensor,形状为 (batch_size, num_max_text_queries, output_dim)) — 通过将投影层应用于 Owlv2TextModel 的池化输出而获得的文本嵌入。
  • image_embeds (torch.FloatTensor,形状为 (batch_size, patch_size, patch_size, output_dim)) — Owlv2VisionModel 的池化输出。OWLv2 将图像表示为一组图像块,并为每个块计算图像嵌入。
  • class_embeds (torch.FloatTensor,形状为 (batch_size, num_patches, hidden_size)) — 所有图像块的类别嵌入。OWLv2 将图像表示为一组图像块,其中块的总数为 (image_size / patch_size)**2。
  • text_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output, 默认为 None) — Owlv2TextModel 的输出。
  • vision_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output, 默认为 None) — Owlv2VisionModel 的输出。

Owlv2ForObjectDetection 的 forward 方法会覆盖 __call__ 特殊方法。

尽管前向传播的流程需要在此函数内定义,但之后应调用 `Module` 实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会默默地忽略它们。

示例

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

>>> from transformers import Owlv2Processor, Owlv2ForObjectDetection

>>> processor = Owlv2Processor.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-base-patch16-ensemble")

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

>>> # Target image sizes (height, width) to rescale box predictions [batch_size, 2]
>>> target_sizes = torch.tensor([(image.height, image.width)])
>>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> results = processor.post_process_grounded_object_detection(
...     outputs=outputs, target_sizes=target_sizes, threshold=0.1, text_labels=text_labels
... )
>>> # Retrieve predictions for the first image for the corresponding text queries
>>> result = results[0]
>>> boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
>>> for box, score, text_label in zip(boxes, scores, text_labels):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected a photo of a cat with confidence 0.614 at location [341.67, 23.39, 642.32, 371.35]
Detected a photo of a cat with confidence 0.665 at location [6.75, 51.96, 326.62, 473.13]

image_guided_detection

< >

( 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, image_size, image_size)) — 对应于输入图像的张量。可以使用 {image_processor_class} 获取像素值。有关详细信息,请参阅 {image_processor_class}.__call__ ({processor_class} 使用 {image_processor_class} 处理图像)。
  • query_pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, height, width)) — 要检测的查询图像的像素值。为每个目标图像传入一个查询图像。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 hidden_states
  • interpolate_pos_encoding (bool, 默认为 False) — 是否对预训练的位置编码进行插值。
  • return_dict (bool, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.models.owlv2.modeling_owlv2.Owlv2ImageGuidedObjectDetectionOutputtuple(torch.FloatTensor)

一个 transformers.models.owlv2.modeling_owlv2.Owlv2ImageGuidedObjectDetectionOutput 或一个 torch.FloatTensor 的元组(如果传递了 return_dict=Falseconfig.return_dict=False),根据配置(Owlv2Config)和输入,包含各种元素。

  • logits (torch.FloatTensor,形状为 (batch_size, num_patches, num_queries)) — 所有查询的分类 logits(包括无对象)。
  • image_embeds (torch.FloatTensor,形状为 (batch_size, patch_size, patch_size, output_dim)) — Owlv2VisionModel 的池化输出。OWLv2 将图像表示为一组图像块,并为每个块计算图像嵌入。
  • query_image_embeds (torch.FloatTensor,形状为 (batch_size, patch_size, patch_size, output_dim)) — Owlv2VisionModel 的池化输出。OWLv2 将图像表示为一组图像块,并为每个块计算图像嵌入。
  • target_pred_boxes (torch.FloatTensor,形状为 (batch_size, num_patches, 4)) — 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每个单独目标图像的大小(不考虑可能的填充)。你可以使用 post_process_object_detection() 来检索未归一化的边界框。
  • query_pred_boxes (torch.FloatTensor,形状为 (batch_size, num_patches, 4)) — 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每个单独查询图像的大小(不考虑可能的填充)。你可以使用 post_process_object_detection() 来检索未归一化的边界框。
  • class_embeds (torch.FloatTensor,形状为 (batch_size, num_patches, hidden_size)) — 所有图像块的类别嵌入。OWLv2 将图像表示为一组图像块,其中块的总数为 (image_size / patch_size)**2。
  • text_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.text_model_output, 默认为 None) — Owlv2TextModel 的输出。
  • vision_model_output (<class '~modeling_outputs.BaseModelOutputWithPooling'>.vision_model_output, 默认为 None) — Owlv2VisionModel 的输出。

示例

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

>>> processor = AutoProcessor.from_pretrained("google/owlv2-base-patch16-ensemble")
>>> model = Owlv2ForObjectDetection.from_pretrained("google/owlv2-base-patch16-ensemble")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> query_url = "http://images.cocodataset.org/val2017/000000001675.jpg"
>>> query_image = Image.open(requests.get(query_url, stream=True).raw)
>>> inputs = processor(images=image, query_images=query_image, return_tensors="pt")

>>> # forward pass
>>> with torch.no_grad():
...     outputs = model.image_guided_detection(**inputs)

>>> target_sizes = torch.Tensor([image.size[::-1]])

>>> # Convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> results = processor.post_process_image_guided_detection(
...     outputs=outputs, threshold=0.9, nms_threshold=0.3, target_sizes=target_sizes
... )
>>> i = 0  # Retrieve predictions for the first image
>>> boxes, scores = results[i]["boxes"], results[i]["scores"]
>>> for box, score in zip(boxes, scores):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected similar object with confidence {round(score.item(), 3)} at location {box}")
Detected similar object with confidence 0.938 at location [327.31, 54.94, 547.39, 268.06]
Detected similar object with confidence 0.959 at location [5.78, 360.65, 619.12, 366.39]
Detected similar object with confidence 0.902 at location [2.85, 360.01, 627.63, 380.8]
Detected similar object with confidence 0.985 at location [176.98, -29.45, 672.69, 182.83]
Detected similar object with confidence 1.0 at location [6.53, 14.35, 624.87, 470.82]
Detected similar object with confidence 0.998 at location [579.98, 29.14, 615.49, 489.05]
Detected similar object with confidence 0.985 at location [206.15, 10.53, 247.74, 466.01]
Detected similar object with confidence 0.947 at location [18.62, 429.72, 646.5, 457.72]
Detected similar object with confidence 0.996 at location [523.88, 20.69, 586.84, 483.18]
Detected similar object with confidence 0.998 at location [3.39, 360.59, 617.29, 499.21]
Detected similar object with confidence 0.969 at location [4.47, 449.05, 614.5, 474.76]
Detected similar object with confidence 0.966 at location [31.44, 463.65, 654.66, 471.07]
Detected similar object with confidence 0.924 at location [30.93, 468.07, 635.35, 475.39]
< > 在 GitHub 上更新