Transformers 文档
OmDet-Turbo
并获得增强的文档体验
开始使用
OmDet-Turbo
概述
OmDet-Turbo 模型由 Tiancheng Zhao, Peng Liu, Xuan He, Lu Zhang, Kyusong Lee 在 Real-time Transformer-based Open-Vocabulary Detection with Efficient Fusion Head 中提出。OmDet-Turbo 结合了 RT-DETR 的组件,并引入了一种快速多模态融合模块,以在保持高精度的同时实现实时开放词汇目标检测能力。该基础模型在 COCO 零样本上实现了高达 100.2 FPS 和 53.4 AP 的性能。
论文摘要如下:
端到端基于 Transformer 的检测器 (DETR) 通过集成语言模态在闭集和开放词汇目标检测 (OVD) 任务中都表现出卓越的性能。然而,其高计算要求阻碍了它们在实时目标检测 (OD) 场景中的实际应用。在本文中,我们审视了 OVDEval 基准中两个领先模型 OmDet 和 Grounding-DINO 的局限性,并引入了 OmDet-Turbo。这个新颖的基于 Transformer 的实时 OVD 模型具有创新的高效融合头 (EFH) 模块,旨在缓解 OmDet 和 Grounding-DINO 中观察到的瓶颈。值得注意的是,OmDet-Turbo-Base 在应用 TensorRT 和语言缓存技术后,实现了 100.2 帧每秒 (FPS) 的速度。在 COCO 和 LVIS 数据集上的零样本场景中,OmDet-Turbo 的性能几乎与当前最先进的监督模型持平。此外,它还在 ODinW 和 OVDEval 上建立了新的最先进基准,AP 分别达到 30.1 和 NMS-AP 达到 26.86。OmDet-Turbo 在基准数据集上卓越的性能和卓越的推理速度突显了其在工业应用中的实用性,使其成为实时目标检测任务的有力选择。

该模型由yonigozlan贡献。原始代码可在此处找到。
使用技巧
与其他零样本目标检测模型(如Grounding DINO)相比,OmDet-Turbo 的一个独特属性是其解耦的类别和提示嵌入结构,允许缓存文本嵌入。这意味着模型需要同时输入类别和任务,其中类别是我们想要检测的对象列表,任务是用于指导开放词汇检测的接地文本。这种方法限制了开放词汇检测的范围,并加快了解码过程。
OmDetTurboProcessor 用于准备类别、任务和图像三元组。任务输入是可选的,如果未提供,将默认为 "检测 [类别1], [类别2], [类别3], ..."
。为了处理模型的输出结果,可以使用 OmDetTurboProcessor 中的 post_process_grounded_object_detection
函数。值得注意的是,该函数接受输入的类别,因为与其他零样本目标检测模型不同,类别和任务嵌入的解耦意味着在后处理步骤中无需对预测的类别嵌入进行解码,预测的类别可以直接与输入的类别匹配。
使用示例
单图像推理
以下是加载模型并准备输入以在单个图像上执行零样本目标检测的方法
>>> import torch
>>> import requests
>>> from PIL import Image
>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection
>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text_labels = ["cat", "remote"]
>>> inputs = processor(image, text=text_labels, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
... outputs,
... target_sizes=[(image.height, image.width)],
... text_labels=text_labels,
... threshold=0.3,
... nms_threshold=0.3,
... )
>>> 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 remote with confidence 0.768 at location [39.89, 70.35, 176.74, 118.04]
Detected cat with confidence 0.72 at location [11.6, 54.19, 314.8, 473.95]
Detected remote with confidence 0.563 at location [333.38, 75.77, 370.7, 187.03]
Detected cat with confidence 0.552 at location [345.15, 23.95, 639.75, 371.67]
多图像推理
OmDet-Turbo 可以执行批处理多图像推理,支持在同一批次中使用不同的文本提示和类别
>>> import torch
>>> import requests
>>> from io import BytesIO
>>> from PIL import Image
>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection
>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> url1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image1 = Image.open(BytesIO(requests.get(url1).content)).convert("RGB")
>>> text_labels1 = ["cat", "remote"]
>>> task1 = "Detect {}.".format(", ".join(text_labels1))
>>> url2 = "http://images.cocodataset.org/train2017/000000257813.jpg"
>>> image2 = Image.open(BytesIO(requests.get(url2).content)).convert("RGB")
>>> text_labels2 = ["boat"]
>>> task2 = "Detect everything that looks like a boat."
>>> url3 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
>>> image3 = Image.open(BytesIO(requests.get(url3).content)).convert("RGB")
>>> text_labels3 = ["statue", "trees"]
>>> task3 = "Focus on the foreground, detect statue and trees."
>>> inputs = processor(
... images=[image1, image2, image3],
... text=[text_labels1, text_labels2, text_labels3],
... task=[task1, task2, task3],
... return_tensors="pt",
... )
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
... outputs,
... text_labels=[text_labels1, text_labels2, text_labels3],
... target_sizes=[(image.height, image.width) for image in [image1, image2, image3]],
... threshold=0.2,
... nms_threshold=0.3,
... )
>>> for i, result in enumerate(results):
... for score, text_label, box in zip(
... result["scores"], result["text_labels"], result["boxes"]
... ):
... box = [round(i, 1) for i in box.tolist()]
... print(
... f"Detected {text_label} with confidence "
... f"{round(score.item(), 2)} at location {box} in image {i}"
... )
Detected remote with confidence 0.77 at location [39.9, 70.4, 176.7, 118.0] in image 0
Detected cat with confidence 0.72 at location [11.6, 54.2, 314.8, 474.0] in image 0
Detected remote with confidence 0.56 at location [333.4, 75.8, 370.7, 187.0] in image 0
Detected cat with confidence 0.55 at location [345.2, 24.0, 639.8, 371.7] in image 0
Detected boat with confidence 0.32 at location [146.9, 219.8, 209.6, 250.7] in image 1
Detected boat with confidence 0.3 at location [319.1, 223.2, 403.2, 238.4] in image 1
Detected boat with confidence 0.27 at location [37.7, 220.3, 84.0, 235.9] in image 1
Detected boat with confidence 0.22 at location [407.9, 207.0, 441.7, 220.2] in image 1
Detected statue with confidence 0.73 at location [544.7, 210.2, 651.9, 502.8] in image 2
Detected trees with confidence 0.25 at location [3.9, 584.3, 391.4, 785.6] in image 2
Detected trees with confidence 0.25 at location [1.4, 621.2, 118.2, 787.8] in image 2
Detected statue with confidence 0.2 at location [428.1, 205.5, 767.3, 759.5] in image 2
OmDetTurboConfig
class transformers.OmDetTurboConfig
< 来源 >( text_config = None backbone_config = None use_timm_backbone = True backbone = 'swin_tiny_patch4_window7_224' backbone_kwargs = None use_pretrained_backbone = False apply_layernorm_after_vision_backbone = True image_size = 640 disable_custom_kernels = False layer_norm_eps = 1e-05 batch_norm_eps = 1e-05 init_std = 0.02 text_projection_in_dim = 512 text_projection_out_dim = 512 task_encoder_hidden_dim = 1024 class_embed_dim = 512 class_distance_type = 'cosine' num_queries = 900 csp_activation = 'silu' conv_norm_activation = 'gelu' encoder_feedforward_activation = 'relu' encoder_feedforward_dropout = 0.0 encoder_dropout = 0.0 hidden_expansion = 1 vision_features_channels = [256, 256, 256] encoder_hidden_dim = 256 encoder_in_channels = [192, 384, 768] encoder_projection_indices = [2] encoder_attention_heads = 8 encoder_dim_feedforward = 2048 encoder_layers = 1 positional_encoding_temperature = 10000 num_feature_levels = 3 decoder_hidden_dim = 256 decoder_num_heads = 8 decoder_num_layers = 6 decoder_activation = 'relu' decoder_dim_feedforward = 2048 decoder_num_points = 4 decoder_dropout = 0.0 eval_size = None learn_initial_query = False cache_size = 100 is_encoder_decoder = True **kwargs )
参数
- text_config (
PretrainedConfig
, 可选) — 文本骨干的配置。 - backbone_config (
PretrainedConfig
, 可选) — 视觉骨干的配置。 - use_timm_backbone (
bool
, 可选, 默认为True
) — 是否使用 timm 作为视觉骨干。 - backbone (
str
, 可选, 默认为"swin_tiny_patch4_window7_224"
) — 要使用的预训练视觉骨干的名称。如果use_pretrained_backbone=False
,则使用具有相同架构backbone
的随机初始化骨干。 - backbone_kwargs (
dict
, 可选) — 视觉骨干的额外关键字参数。 - use_pretrained_backbone (
bool
, 可选, 默认为False
) — 是否使用预训练的视觉骨干。 - apply_layernorm_after_vision_backbone (
bool
, 可选, 默认为True
) — 是否在视觉骨干输出的特征图上应用层归一化。 - image_size (
int
, 可选, 默认为 640) — 每张图像的大小(分辨率)。 - disable_custom_kernels (
bool
, 可选, 默认为False
) — 是否禁用自定义内核。 - layer_norm_eps (
float
, 可选, 默认为 1e-05) — 层归一化的 epsilon 值。 - batch_norm_eps (
float
, 可选, 默认为 1e-05) — 批归一化的 epsilon 值。 - init_std (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - text_projection_in_dim (
int
, 可选, 默认为 512) — 文本投影的输入维度。 - text_projection_out_dim (
int
, 可选, 默认为 512) — 文本投影的输出维度。 - task_encoder_hidden_dim (
int
, 可选, 默认为 1024) — 任务编码器的前馈维度。 - class_embed_dim (
int
, 可选, 默认为 512) — 类别嵌入的维度。 - class_distance_type (
str
, 可选, 默认为"cosine"
) — 用于将预测类别与投影类别嵌入进行比较的距离类型。可以是"cosine"
或"dot"
。 - num_queries (
int
, 可选, 默认为 900) — 查询的数量。 - csp_activation (
str
, 可选, 默认为"silu"
) — 编码器交叉阶段部分 (CSP) 网络的激活函数。 - conv_norm_activation (
str
, 可选, 默认为"gelu"
) — 编码器 ConvNormLayer 层的激活函数。 - encoder_feedforward_activation (
str
, 可选, 默认为"relu"
) — 编码器前馈网络的激活函数。 - encoder_feedforward_dropout (
float
, 可选, 默认为 0.0) — 编码器前馈网络激活后的 dropout 率。 - encoder_dropout (
float
, 可选, 默认为 0.0) — 编码器多头注意力模块的 dropout 率。 - hidden_expansion (
int
, 可选, 默认为 1) — 编码器中 CSP 网络的隐藏扩展。 - vision_features_channels (
tuple(int)
, 可选, 默认为[256, 256, 256]
) — 用作解码器输入的投影视觉特征通道。 - encoder_hidden_dim (
int
, 可选, 默认为 256) — 编码器的隐藏维度。 - encoder_in_channels (
List(int)
, 可选, 默认为[192, 384, 768]
) — 编码器的输入通道。 - encoder_projection_indices (
List(int)
, 可选, 默认为[2]
) — 每个层投影的输入特征的索引。 - encoder_attention_heads (
int
, 可选, 默认为 8) — 编码器的注意力头数量。 - encoder_dim_feedforward (
int
, 可选, 默认为 2048) — 编码器的前馈维度。 - encoder_layers (
int
, 可选, 默认为 1) — 编码器中的层数。 - positional_encoding_temperature (
int
, 可选, 默认为 10000) — 编码器中的位置编码温度。 - num_feature_levels (
int
, 可选, 默认为 3) — 解码器多尺度可变形注意力模块的特征层数。 - decoder_hidden_dim (
int
, 可选, 默认为 256) — 解码器的隐藏维度。 - decoder_num_heads (
int
, 可选, 默认为 8) — 解码器的头数量。 - decoder_num_layers (
int
, 可选, 默认为 6) — 解码器的层数。 - decoder_activation (
str
, 可选, 默认为"relu"
) — 解码器的激活函数。 - decoder_dim_feedforward (
int
, 可选, 默认为 2048) — 解码器的前馈维度。 - decoder_num_points (
int
, 可选, 默认为 4) — 在解码器多尺度可变形注意力模块中采样的点数。 - decoder_dropout (
float
, 可选, 默认为 0.0) — 解码器的 dropout 率。 - eval_size (
tuple[int, int]
, 可选) — 用于计算考虑步幅后位置嵌入的有效高度和宽度的尺寸(请参见 RTDetr)。 - learn_initial_query (
bool
, 可选, 默认为False
) — 是否学习初始查询。 - cache_size (
int
, 可选, 默认为 100) — 类别和提示缓存的缓存大小。 - is_encoder_decoder (
bool
, 可选, 默认为True
) — 模型是否用作编码器-解码器模型。 - kwargs (
dict[str, Any]
, 可选) — 架构中的其他参数。kwargs 中的值将作为配置的一部分保存,可用于控制模型输出。
这是一个配置类,用于存储 OmDetTurboForObjectDetection 的配置。它用于根据指定的参数实例化 OmDet-Turbo 模型,定义模型架构。使用默认值实例化配置将产生类似于 OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf 架构的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PretrainedConfig 的文档。
示例
>>> from transformers import OmDetTurboConfig, OmDetTurboForObjectDetection
>>> # Initializing a OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf style configuration
>>> configuration = OmDetTurboConfig()
>>> # Initializing a model (with random weights) from the omlab/omdet-turbo-swin-tiny-hf style configuration
>>> model = OmDetTurboForObjectDetection(configuration)
>>> # Accessing the model configuration
>>> configuration = model.config
OmDetTurboProcessor
class transformers.OmDetTurboProcessor
< 源 >( image_processor tokenizer )
参数
- image_processor (
DetrImageProcessor
) — DetrImageProcessor 的实例。图像处理器是必需输入。 - tokenizer (
AutoTokenizer
) — [‘PreTrainedTokenizer`] 的实例。分词器是必需输入。
构建一个 OmDet-Turbo 处理器,它将可变形 DETR 图像处理器和 AutoTokenizer 封装到一个处理器中。
OmDetTurboProcessor 提供 DetrImageProcessor 和 AutoTokenizer 的所有功能。有关更多信息,请参阅 __call__()
和 decode()
的文档字符串。
post_process_grounded_object_detection
< 源 >( outputs: OmDetTurboObjectDetectionOutput text_labels: typing.Union[list[str], list[list[str]], NoneType] = None threshold: float = 0.3 nms_threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None max_num_det: typing.Optional[int] = None ) → list[Dict]
参数
- outputs (
OmDetTurboObjectDetectionOutput
) — 模型的原始输出。 - text_labels (Union[list[str], list[list[str]]], 可选) — 输入的类别名称。如果未提供,
text_labels
将在outputs
中设置为None
。 - threshold (float, 默认为 0.3) — 仅返回置信度得分超过此阈值的检测结果。
- nms_threshold (float, 默认为 0.5) — 用于边界框非极大值抑制的阈值。值介于 [0, 1] 之间。
- target_sizes (
torch.Tensor
或list[tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或包含批次中每张图像目标大小(height, width)
的元组列表(tuple[int, int]
)。如果未设置,预测将不会被调整大小。 - max_num_det (
int
, 可选) — 返回的最大检测数量。
返回
list[Dict]
一个字典列表,每个字典包含模型预测的批次中图像的分数、类别和边界框。
将 OmDetTurboForObjectDetection 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框,并获取相关的文本类别。
OmDetTurboForObjectDetection
class transformers.OmDetTurboForObjectDetection
< 源 >( config: OmDetTurboConfig )
参数
- config (OmDetTurboConfig) — 包含模型所有参数的模型配置类。使用配置文件初始化并不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法来加载模型权重。
OmDetTurbo 模型(由视觉和文本骨干,以及编码器-解码器架构组成)输出用于 COCO 检测等任务的边界框和类别分数。
该模型继承自 PreTrainedModel。请查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是 PyTorch torch.nn.Module 的子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档以了解所有与一般使用和行为相关的事项。
前向
< 源 >( pixel_values: FloatTensor classes_input_ids: LongTensor classes_attention_mask: LongTensor tasks_input_ids: LongTensor tasks_attention_mask: LongTensor classes_structure: LongTensor labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutput
或 tuple(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}
处理图像)。 - classes_input_ids (
torch.LongTensor
,形状为(total_classes (>= batch_size), sequence_length)
) — 语言模型词汇表中输入类别序列 token 的索引。每个任务可以提供多个类别,因此 tokenized 类别是扁平的,类别结构在classes_structure
参数中提供。索引可以使用 OmDetTurboProcessor 获取。有关详细信息,请参见
OmDetTurboProcessor.__call__()
。 - classes_attention_mask (
torch.BoolTensor
,形状为(total_classes (>= batch_size), num_classes, sequence_length)
) — 类别的注意力掩码。这是一个二进制掩码,指示应关注哪些 token,不应关注哪些 token。 - tasks_input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 语言模型词汇表中输入任务序列 token 的索引。索引可以使用 OmDetTurboProcessor 获取。有关详细信息,请参见
OmDetTurboProcessor.__call__()
。 - tasks_attention_mask (
torch.BoolTensor
,形状为(batch_size, sequence_length)
) — 任务的注意力掩码。这是一个二进制掩码,指示应关注哪些 token,不应关注哪些 token。 - classes_structure (
torch.LongTensor
,形状为(batch_size)
) — 类别的结构。此张量指示每个任务的类别数量。 - labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
, 可选) — 用于计算掩码语言建模损失的标签。索引应为[0, ..., config.vocab_size]
或 -100(请参见input_ids
文档字符串)。索引设置为-100
的 token 将被忽略(掩码),损失仅针对标签在[0, ..., config.vocab_size]
中的 token 计算。 - output_attentions (
bool
, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的attentions
。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是纯元组。
返回
transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutput
或 tuple(torch.FloatTensor)
一个 transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutput
或 torch.FloatTensor
元组(如果传递 return_dict=False
或当 config.return_dict=False
时),包含取决于配置 (OmDetTurboConfig) 和输入的各种元素。
- loss (
torch.FloatTensor
, 可选, 默认为None
) — 损失值。 - decoder_coord_logits (
torch.FloatTensor
,形状为(batch_size, num_queries, 4)
) — 对象的预测坐标对数。 - decoder_class_logits (
torch.FloatTensor
,形状为(batch_size, num_queries, num_classes)
) — 对象的预测类别。 - init_reference_points (
torch.FloatTensor
,形状为(batch_size, num_queries, 4)
) — 初始参考点。 - intermediate_reference_points (
tuple[tuple[torch.FloatTensor]]
, 可选, 默认为None
) — 中间参考点。 - encoder_coord_logits (
torch.FloatTensor
,形状为(batch_size, num_queries, 4)
) — 编码器预测的对象的坐标。 - encoder_class_logits (
tuple[torch.FloatTensor].encoder_class_logits
, 默认为None
) — 编码器预测的对象的类别。 - encoder_extracted_states (
torch.FloatTensor
, 可选, 默认为None
) — 从编码器的特征金字塔网络 (FPN) 和路径聚合网络 (PAN) 中提取的状态。 - decoder_hidden_states (
tuple[torch.FloatTensor]
, 可选) —torch.FloatTensor
元组(一个用于嵌入输出 + 一个用于每层输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态以及初始嵌入输出。 - decoder_attentions (
tuple[tuple[torch.FloatTensor]]
, 可选) —torch.FloatTensor
元组(每层一个注意力),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力、交叉注意力和多尺度可变形注意力头中的加权平均值。 - encoder_hidden_states (
tuple[torch.FloatTensor]
, 可选) —torch.FloatTensor
元组(一个用于嵌入输出 + 一个用于每层输出),形状为(batch_size, sequence_length, hidden_size)
。模型在每层输出处的隐藏状态以及初始嵌入输出。 - encoder_attentions (
tuple[tuple[torch.FloatTensor]]
, 可选) —torch.FloatTensor
元组(每层一个注意力),形状为(batch_size, num_heads, sequence_length, sequence_length)
。注意力 softmax 后的注意力权重,用于计算自注意力、交叉注意力和多尺度可变形注意力头中的加权平均值。 - classes_structure (
torch.LongTensor
, 可选) — 每张图像查询的类别数量。
OmDetTurboForObjectDetection 前向方法,覆盖 __call__
特殊方法。
尽管前向传播的配方需要在此函数中定义,但在此之后应调用 Module
实例,而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。
示例
>>> import requests
>>> from PIL import Image
>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection
>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> classes = ["cat", "remote"]
>>> task = "Detect {}.".format(", ".join(classes))
>>> inputs = processor(image, text=classes, task=task, return_tensors="pt")
>>> outputs = model(**inputs)
>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
... outputs,
... classes=classes,
... target_sizes=[image.size[::-1]],
... score_threshold=0.3,
... nms_threshold=0.3,
>>> )[0]
>>> for score, class_name, box in zip(results["scores"], results["classes"], results["boxes"]):
... box = [round(i, 1) for i in box.tolist()]
... print(
... f"Detected {class_name} with confidence "
... f"{round(score.item(), 2)} at location {box}"
... )
Detected remote with confidence 0.76 at location [39.9, 71.3, 176.5, 117.9]
Detected cat with confidence 0.72 at location [345.1, 22.5, 639.7, 371.9]
Detected cat with confidence 0.65 at location [12.7, 53.8, 315.5, 475.3]
Detected remote with confidence 0.57 at location [333.4, 75.6, 370.7, 187.0]