Transformers documentation

OWLv2

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.1).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

该模型于 2023-06-16 在 HF papers 上发布,并于 2023-10-13 贡献至 Hugging Face Transformers。

OWLv2

概述

OWLv2 由 Matthias Minderer、Alexey Gritsenko 和 Neil Houlsby 在 Scaling Open-Vocabulary Object Detection 中提出。OWLv2 通过自训练对 OWL-ViT 进行扩展,该过程利用现有检测器在图文对上生成伪框标注。这使得零样本目标检测的性能相较于此前的最先进方法有了显著提升。

该论文的摘要如下:

开放词汇目标检测已从预训练的视觉-语言模型中受益匪浅,但仍受限于可用的检测训练数据量。虽然可以利用网络图像-文本对作为弱监督来扩充检测训练数据,但这一做法尚未达到与图像级预训练相当的数据规模。在此,我们通过自训练来扩展检测数据,该方法利用现有的检测器在图像-文本对上生成伪框标注。在扩展自训练过程中,主要挑战在于标签空间的选择、伪标注的过滤以及训练效率。我们提出了 OWLv2 模型和 OWL-ST 自训练方案,以应对这些挑战。在相当的训练规模(约 1000 万样本)下,OWLv2 的性能已超越了此前最先进的开放词汇检测器。然而,借助 OWL-ST,我们可以将数据规模扩展至超过 10 亿样本,从而带来进一步的显著提升:采用 L/14 架构时,OWL-ST 将 LVIS 稀有类别上的 AP 从 31.2% 提升至 44.6%(相对提升 43%),而模型在这些类别上从未见过任何人工框标注。OWL-ST 为开放世界定位解锁了网络规模的训练,这与图像分类和语言建模领域所观察到的趋势类似。

drawing OWLv2 high-level overview. Taken from the original paper.

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

使用示例

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

Owlv2ImageProcessor 可用于对图像进行缩放(或重新缩放)和归一化,以适配模型,而 CLIPTokenizer 用于对文本进行编码。Owlv2Processor 将 Owlv2ImageProcessor 和 CLIPTokenizer 封装为单一实例,同时完成文本编码和图像预处理。以下示例展示了如何使用 Owlv2Processor 和 Owlv2ForObjectDetection 执行目标检测。

import requests
from PIL import Image
import torch

from transformers import Owlv2Processor, Owlv2ForObjectDetection

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

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").to(model.device)
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

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonereturn_dict: bool = Truetext_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonevision_config: dict | transformers.configuration_utils.PreTrainedConfig | None = Noneprojection_dim: int = 512logit_scale_init_value: float = 2.6592initializer_factor: float = 1.0 )

参数

  • return_dict (bool,可选,默认为 True) — 是否返回 ModelOutput(dataclass)而不是普通的元组。
  • text_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 文本骨干网络的配置对象或字典。
  • vision_config (Union[dict, ~configuration_utils.PreTrainedConfig],可选) — 视觉骨干网络的配置对象或字典。
  • projection_dim (int,可选,默认为 512) — 文本和视觉投影层的维度。
  • logit_scale_init_value (float,可选,默认为 2.6592) — logit_scale 参数的初始值。
  • initializer_factor (float,可选,默认为 1.0) — 用于初始化所有权重矩阵的系数(应保持为 1,内部用于初始化测试)。

这是用于存储 Owlv2Model 配置的类。它根据指定的参数实例化 Owlv2 模型,并定义模型架构。使用默认值实例化配置将生成与 google/owlv2-base-patch16 类似的配置。

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

Owlv2TextConfig

class transformers.Owlv2TextConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonevocab_size: int = 49408hidden_size: int = 512intermediate_size: int = 2048num_hidden_layers: int = 12num_attention_heads: int = 8max_position_embeddings: int = 16hidden_act: str = 'quick_gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0initializer_range: float = 0.02initializer_factor: float = 1.0pad_token_id: int | None = 0bos_token_id: int | None = 49406eos_token_id: int | list[int] | None = 49407 )

参数

  • vocab_size (int,可选,默认为 49408) — 模型的词汇表大小。定义了 input_ids 可以表示的不同 token 数量。
  • hidden_size (int,可选,默认为 512) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 2048) — MLP 表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • max_position_embeddings (int,可选,默认为 16) — 该模型可能使用的最大序列长度。
  • hidden_act (str,可选,默认为 quick_gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 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 (Union[int, list[int]],可选,默认为 49407) — 词汇表中用于表示流结束(end-of-stream)的 token id。

这是用于存储 Owlv2Model 配置的类。它根据指定的参数实例化 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

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonehidden_size: int = 768intermediate_size: int = 3072num_hidden_layers: int = 12num_attention_heads: int = 12num_channels: int = 3image_size: int | list[int] | tuple[int, int] = 768patch_size: int | list[int] | tuple[int, int] = 16hidden_act: str = 'quick_gelu'layer_norm_eps: float = 1e-05attention_dropout: float | int = 0.0initializer_range: float = 0.02initializer_factor: float = 1.0 )

参数

  • hidden_size (int,可选,默认为 768) — 隐藏表示的维度。
  • intermediate_size (int,可选,默认为 3072) — MLP 表示的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 解码器中的隐藏层数量。
  • num_attention_heads (int,可选,默认为 12) — Transformer 解码器中每个注意力层的注意力头数量。
  • num_channels (int,可选,默认为 3) — 输入通道的数量。
  • image_size (Union[int, list[int], tuple[int, int]],可选,默认为 768) — 每张图片的尺寸(分辨率)。
  • patch_size (Union[int, list[int], tuple[int, int]],可选,默认为 16) — 每个 patch 的大小(分辨率)。
  • hidden_act (str,可选,默认为 quick_gelu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、 "relu"、"silu" 等。
  • layer_norm_eps (float,可选,默认为 1e-05) — 层归一化层所使用的 epsilon 值。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • initializer_factor (float,可选,默认为 1.0) — 用于初始化所有权重矩阵的系数(应保持为 1,内部用于初始化测试)。

这是用于存储 Owlv2Model 配置的类。它根据指定的参数实例化 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

< >

( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 960, 'width': 960}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 None) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为 [0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选,默认为 None) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

构建一个 Owlv2ImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~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。
  • image_like_kwargs (dict[str, Any], 可选) — 用于额外图像类输入的开发者标志,这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如,preprocess(images, masks=masks) 是首选方式,但对于某些模型会导致参数优先级问题。在这种情况下,可以改用 preprocess(images, image_like_inputs={"masks": masks})。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

post_process_object_detection

< >

( outputs: Owlv2ObjectDetectionOutputthreshold: float = 0.1target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None ) → list[Dict]

参数

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

将 Owlv2ForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。

post_process_image_guided_detection

< >

( outputsthreshold = 0.0nms_threshold = 0.3target_sizes = None ) → list[Dict]

参数

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

返回值

list[Dict]

一个字典列表,每个字典包含模型在批次中为一张图像预测的分数、标签和边界框。由于 Owlv2ForObjectDetection.image_guided_detection 执行单步目标检测,所有标签均被设置为 None。

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

Owlv2ImageProcessorPil

class transformers.Owlv2ImageProcessorPil

< >

( **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选,默认为 True) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 {'height' -- 960, 'width': 960}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 True) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs,默认为 None) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 True) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]],kwargs,可选,默认为 [0.48145466, 0.4578275, 0.40821073]) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选,默认为 [0.26862954, 0.26130258, 0.27577711]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool,kwargs,可选,默认为 True) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选,默认为 None) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

构建一个 Owlv2ImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~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。
  • image_like_kwargs (dict[str, Any], 可选) — 用于额外图像类输入的开发者标志,这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如,preprocess(images, masks=masks) 是首选方式,但对于某些模型会导致参数优先级问题。在这种情况下,可以改用 preprocess(images, image_like_inputs={"masks": masks})。
  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 描述模型的最大输入维度。
  • default_to_square (bool, kwargs, 可选) — 当 size 为整数时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时生效。
  • do_rescale (bool,kwargs,可选) — 是否对图像进行重新缩放。
  • rescale_factor (float, kwargs, 可选) — 如果 do_rescale 设置为 True,则用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选) — 是否对图像进行归一化。
  • image_mean (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时生效。
  • image_std (Union[float, list[float], tuple[float, ...]], kwargs, 可选) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时生效。
  • do_pad (bool, kwargs, 可选) — 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸,或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 用于填充图像的 {"height": int, "width" int} 尺寸。必须大于为预处理提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True. 时应用。
  • do_center_crop (bool,kwargs,可选) — 是否对图像进行中心裁剪。
  • data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 仅支持 ChannelDimension.FIRST。为兼容旧版处理器而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension], kwargs, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
    • "none" 或 ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (Annotated[Union[str, torch.device, NoneType], None], kwargs) — 用于处理视频的设备。如果未设置,则从输入视频中推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None], kwargs) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool,kwargs,可选) — 是否禁用按尺寸对图像进行分组,从而逐个处理图像而非批量处理。 如果为 None,则当图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见此处:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int,kwargs,可选) — 输入中每张图片所使用的图像 token 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

post_process_object_detection

< >

( outputs: Owlv2ObjectDetectionOutputthreshold: float = 0.1target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None ) → list[Dict]

参数

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

将 Owlv2ForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。

post_process_image_guided_detection

< >

( outputsthreshold = 0.0nms_threshold = 0.3target_sizes = None ) → list[Dict]

参数

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

返回值

list[Dict]

一个字典列表,每个字典包含模型在批次中为一张图像预测的分数、标签和边界框。由于 Owlv2ForObjectDetection.image_guided_detection 执行单步目标检测,所有标签均被设置为 None。

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

Owlv2Processor

class transformers.Owlv2Processor

< >

( image_processortokenizer**kwargs )

参数

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

构造一个 Owlv2Processor,将图像处理器和分词器封装为单一处理器。

Owlv2Processor 提供了 Owlv2ImageProcessor 和 CLIPTokenizer 的所有功能。有关更多信息,请参阅 ~Owlv2ImageProcessor 和 ~CLIPTokenizer。

__call__

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = Nonetext: str | list[str] | list[list[str]] = None**kwargs: *<class 'transformers.models.owlv2.processing_owlv2.Owlv2ProcessorKwargs'> ) → 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。
  • text (Union[str, list[str], list[list[str]]],可选) — 要编码的序列或序列批次。每个序列可以是字符串或字符串列表(预分词字符串)。如果传入预分词输入,请设置 is_split_into_words=True,以避免与批量输入产生歧义。
  • query_images (ImageInput, kwargs, 可选) — 用于图像引导目标检测的查询图像。提供后,这些图像将作为视觉查询,用于在主 images 中查找相似的目标。查询图像会覆盖任何文本提示,模型将执行图像到图像的匹配,而非文本到图像的匹配。
  • return_tensors (str 或 TensorType, 可选) — 如果设置,将返回特定框架的张量。可接受的值为:
    • 'pt':返回 PyTorch torch.Tensor 对象。
    • 'np':返回 NumPy np.ndarray 对象。
  • **kwargs (ProcessingKwargs,可选) — 每种模态(文本、图像、视频、音频)的额外处理选项。模型特定参数已在上方列出;有关支持参数的完整列表,请参阅 TypedDict 类。

返回值

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 时返回。

post_process_grounded_object_detection

< >

( outputs: Owlv2ObjectDetectionOutputthreshold: float = 0.1target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = Nonetext_labels: list[list[str]] | None = None ) → list[Dict]

参数

  • outputs (Owlv2ObjectDetectionOutput) — 模型的原始输出。
  • threshold (float,可选,默认为 0.1) — 用于保留目标检测预测结果的分数阈值。
  • target_sizes (torch.Tensor 或 list[tuple[int, int]],可选) — 形状为 (batch_size, 2) 的张量,或包含目标尺寸 (height, width) 的元组列表(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: Owlv2ImageGuidedObjectDetectionOutputthreshold: float = 0.0nms_threshold: float = 0.3target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None ) → list[Dict]

参数

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

返回值

list[Dict]

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

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

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

Owlv2Model

class transformers.Owlv2Model

< >

( config: Owlv2Config )

参数

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

未添加任何特定头部的裸 Owlv2 模型,输出原始隐藏状态。

该模型继承自 PreTrainedModel。请查阅父类文档,了解该库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、剪枝头等)。

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( input_ids: typing.Optional[torch.LongTensor] = Nonepixel_values: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = Nonereturn_loss: bool | None = Noneinterpolate_pos_encoding: bool = Falsereturn_base_image_embeds: bool | None = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Owlv2Output or tuple(torch.Tensor)

参数

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

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

    什么是输入 ID?

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Owlv2ImageProcessor 获取像素值。有关详细信息,请参阅 Owlv2ImageProcessor.call()(Owlv2Processor 使用 Owlv2ImageProcessor 来处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • return_loss (bool, 可选) — 是否返回对比损失。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。
  • return_base_image_embeds (bool,可选) — 是否返回基础图像嵌入。

返回值

Owlv2Output 或 tuple(torch.Tensor)

Owlv2Output 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Owlv2Config)和输入。

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

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选,当 return_loss 为 True 时返回) — 用于图像-文本相似度的对比损失。
  • logits_per_image(形状为 (image_batch_size, text_batch_size) 的 torch.Tensor)— image_embeds 与 text_embeds 之间的缩放点积分数。这表示图像-文本相似度分数。
  • logits_per_text(形状为 (text_batch_size, image_batch_size) 的 torch.Tensor)— text_embeds 与 image_embeds 之间的缩放点积分数。这表示文本-图像相似度分数。
  • text_embeds(形状为 (batch_size * num_max_text_queries, output_dim 的 torch.Tensor)—— 通过对 Owlv2TextModel 的池化输出应用投影层获得的文本嵌入。
  • image_embeds (torch.Tensor,形状为 (batch_size, output_dim) — 通过对 Owlv2VisionModel 的池化输出应用投影层得到的图像嵌入。
  • text_model_output (~modeling_outputs.BaseModelOutputWithPooling,可选) — Owlv2TextModel 的输出。
  • vision_model_output(~modeling_outputs.BaseModelOutputWithPooling,可选)— Owlv2VisionModel 的输出。

示例:

>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> 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"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> 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: Tensorattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_ids(形状为 (batch_size * num_max_text_queries, sequence_length) 的 torch.LongTensor)— 输入序列中各个 token 在词汇表中的索引。可以使用 AutoTokenizer 获取这些索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是输入 ID?
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Owlv2Config)和输入。

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

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

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

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

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

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

示例:

>>> import torch
>>> 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"
... )
>>> with torch.inference_mode():
...     text_features = model.get_text_features(**inputs)

get_image_features

< >

( pixel_values: Tensorinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Owlv2ImageProcessor 获取像素值。有关详细信息,请参阅 Owlv2ImageProcessor.call()(Owlv2Processor 使用 Owlv2ImageProcessor 处理图像)。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Owlv2Config)和输入。

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

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

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

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

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

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

示例:

>>> import torch
>>> from transformers.image_utils import load_image
>>> 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 = load_image(url)

>>> inputs = processor(images=image, return_tensors="pt")
>>> with torch.inference_mode():
...     image_features = model.get_image_features(**inputs)

Owlv2TextModel

class transformers.Owlv2TextModel

< >

( config: Owlv2TextConfig )

forward

< >

( input_ids: typing.Optional[torch.Tensor] = Noneattention_mask: typing.Optional[torch.Tensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • input_ids(形状为 (batch_size * num_max_text_queries, sequence_length) 的 torch.LongTensor)— 输入序列中各个 token 在词汇表中的索引。可以使用 AutoTokenizer 获取这些索引。有关详细信息,请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是输入 ID?
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Owlv2Config)和输入。

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

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

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

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

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

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

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

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

示例:

>>> 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.Tensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BaseModelOutputWithPooling or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size),可选) — 与输入图像对应的张量。可以使用 Owlv2ImageProcessor 获取像素值。有关详细信息,请参阅 Owlv2ImageProcessor.call()(Owlv2Processor 使用 Owlv2ImageProcessor 来处理图像)。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

BaseModelOutputWithPooling 或 tuple(torch.Tensor)

一个 BaseModelOutputWithPooling 或 torch.Tensor 元组(如果传入了 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(Owlv2Config)和输入。

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

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

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

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

  • hidden_states (tuple(torch.Tensor),可选,当传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(如果模型具有嵌入层,则包含嵌入层的输出,以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size)。

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

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

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

示例:

>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> 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"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> 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: Tensorpixel_values: Tensorattention_mask: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Owlv2ObjectDetectionOutput or tuple(torch.Tensor)

参数

  • input_ids(形状为 (batch_size * num_max_text_queries, sequence_length) 的 torch.LongTensor,可选) — 输入序列中各 token 在词汇表中的索引。可通过 AutoTokenizer 获取这些索引。详情请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。什么是输入 ID?
  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Owlv2ImageProcessor 获取像素值。有关详细信息,请参阅 Owlv2ImageProcessor.call()(Owlv2Processor 使用 Owlv2ImageProcessor 处理图像)。
  • attention_mask (torch.Tensor 形状为 (batch_size, sequence_length), ,可选) — 用于避免对填充 token 索引执行注意力机制的掩码。掩码值取自 [0, 1]:
    • 1 表示未被屏蔽的 token,
    • 对于被掩码的 token,值为 0。

    什么是注意力掩码?

  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

Owlv2ObjectDetectionOutput 或 tuple(torch.Tensor)

Owlv2ObjectDetectionOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Owlv2Config)和输入。

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

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

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

示例:

>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> 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"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> 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: Tensorquery_pixel_values: typing.Optional[torch.Tensor] = Noneinterpolate_pos_encoding: bool = False**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → Owlv2ImageGuidedObjectDetectionOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应输入图像的张量。可以使用 Owlv2ImageProcessor 获取像素值。有关详细信息,请参阅 Owlv2ImageProcessor.call()(Owlv2Processor 使用 Owlv2ImageProcessor 处理图像)。
  • query_pixel_values (torch.Tensor,形状为 (batch_size, num_channels, height, width)) — 待检测查询图像的像素值。请为每个目标图像传入一张查询图像。
  • interpolate_pos_encoding (bool,可选,默认为 False) — 是否对预训练的位置编码进行插值。

返回值

Owlv2ImageGuidedObjectDetectionOutput 或 tuple(torch.Tensor)

Owlv2ImageGuidedObjectDetectionOutput 或 torch.Tensor 元组(当传入 return_dict=False 或 config.return_dict=False 时),其包含的元素取决于配置(Owlv2Config)和输入。

  • logits(形状为 (batch_size, num_patches, num_queries) 的 torch.Tensor)— 所有查询的分类 logits(包括无对象)。
  • image_embeds (torch.Tensor,形状为 (batch_size, patch_size, patch_size, output_dim) — Owlv2VisionModel 的池化输出。OWLv2 将图像表示为一组图像块(image patches),并为每个图像块计算图像嵌入。
  • query_image_embeds (torch.Tensor,形状为 (batch_size, patch_size, patch_size, output_dim) — Owlv2VisionModel 的池化输出。OWLv2 将图像表示为一组图像块(image patches),并为每个图像块计算图像嵌入。
  • target_pred_boxes(形状为 (batch_size, num_patches, 4) 的 torch.Tensor)— 所有查询的归一化框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每个目标图像的尺寸(忽略可能的填充)。您可以使用 post_process_object_detection() 来获取未归一化的边界框。
  • query_pred_boxes(形状为 (batch_size, num_patches, 4) 的 torch.Tensor)— 所有查询的归一化边界框坐标,表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化,相对于批次中每个查询图像各自的尺寸(忽略可能的填充)。您可以使用 post_process_object_detection() 来获取未归一化的边界框。
  • class_embeds (torch.Tensor,形状为 (batch_size, num_patches, hidden_size)) — 所有图像块的类别嵌入。OWLv2 将图像表示为一组图像块,其中图像块的总数为 (image_size / patch_size)**2。
  • text_model_output (~modeling_outputs.BaseModelOutputWithPooling,可选) — Owlv2TextModel 的输出。
  • vision_model_output(~modeling_outputs.BaseModelOutputWithPooling,可选)— Owlv2VisionModel 的输出。

示例:

>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> 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"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> query_url = "http://images.cocodataset.org/val2017/000000001675.jpg"
>>> with httpx.stream("GET", query_url) as response:
...     query_image = Image.open(BytesIO(response.read()))
>>> 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 1.0 at location [341.76, 22.77, 640.65, 370.25]
Detected similar object with confidence 1.0 at location [6.59, 51.43, 329.05, 476.77]
Update on GitHub