# Grounding DINO

## 概述

Grounding DINO 模型由 Shilong Liu、Zhaoyang Zeng、Tianhe Ren、Feng Li、Hao Zhang、Jie Yang、Chunyuan Li、Jianwei Yang、Hang Su、Jun Zhu 和 Lei Zhang 在 [Grounding DINO: Marrying DINO with Grounded Pre-Training for Open-Set Object Detection](https://huggingface.co/papers/2303.05499) 中提出。Grounding DINO 通过为闭集目标检测模型添加文本编码器，实现了开放集目标检测。该模型取得了显著的成果，例如在 COCO 零样本任务上达到了 52.5 AP。

该论文的摘要如下：

*本文提出了一种名为 Grounding DINO 的开放集目标检测器，它将基于 Transformer 的检测器 DINO 与基于文本的预训练相结合，能够根据类别名称或指代表达式等人类输入检测任意目标。开放集目标检测的关键在于向闭集检测器引入语言，以实现开放集概念的泛化。为了有效融合语言和视觉模态，我们在概念上将闭集检测器划分为三个阶段，并提出了一种紧密融合方案，其中包括特征增强器、语言引导的查询选择以及用于跨模态融合的跨模态解码器。尽管以往的工作主要在新型类别上评估开放集目标检测，我们建议针对具有属性指定的目标，也进行指代表达式理解的评估。Grounding DINO 在所有三种设置下均表现出色，包括在 COCO、LVIS、ODinW 和 RefCOCO/+/g 上的基准测试。Grounding DINO 在 COCO 检测零样本迁移基准上取得了 52.5 AP 的成绩，即未使用任何来自 COCO 的训练数据。它在 ODinW 零样本基准上创下了新纪录，平均 AP 达到 26.1。*

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/grouding_dino_architecture.png"
alt="drawing" width="600"/>

 Grounding DINO 概览。摘自原始论文。

该模型由 [EduardoPacheco](https://huggingface.co/EduardoPacheco) 和 [nielsr](https://huggingface.co/nielsr) 贡献。原始代码可在[此处](https://github.com/IDEA-Research/GroundingDINO)找到。

## 使用技巧

- 可以使用 [GroundingDinoProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoProcessor) 为模型准备图像-文本对。
- 要在文本中分隔类别，请使用句号，例如 "a cat. a dog."
- 当使用多个类别（例如 `"a cat. a dog."`）时，请使用 [GroundingDinoProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoProcessor) 中的 `post_process_grounded_object_detection` 对输出进行后处理。因为 `post_process_object_detection` 返回的标签表示模型维度中 prob > threshold 的索引。

以下是如何使用该模型进行零样本目标检测：

```python
import requests

import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection

model_id = "IDEA-Research/grounding-dino-tiny"

processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id, device_map="auto")

image_url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(image_url, stream=True).raw)
# Check for cats and remote controls
text_labels = [["a cat", "a remote control"]]

inputs = processor(images=image, text=text_labels, return_tensors="pt").to(model.device)
with torch.no_grad():
    outputs = model(**inputs)

results = processor.post_process_grounded_object_detection(
    outputs,
    inputs.input_ids,
    threshold=0.4,
    text_threshold=0.3,
    target_sizes=[image.size[::-1]]
)

# Retrieve the first image result
result = results[0]
for box, score, labels in zip(result["boxes"], result["scores"], result["labels"]):
    box = [round(x, 2) for x in box.tolist()]
    print(f"Detected {labels} with confidence {round(score.item(), 3)} at location {box}")
Detected a cat with confidence 0.468 at location [344.78, 22.9, 637.3, 373.62]
Detected a cat with confidence 0.426 at location [11.74, 51.55, 316.51, 473.22]
```

## Grounded SAM

可以将 Grounding DINO 与 [Segment Anything](sam) 模型结合，以实现基于文本的掩码生成，如 [Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks](https://huggingface.co/papers/2401.14159) 中所述。有关详细信息，请参阅此 [演示笔记本](https://github.com/NielsRogge/Transformers-Tutorials/blob/master/Grounding%20DINO/GroundingDINO_with_Segment_Anything.ipynb) 🌍。

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/grounded_sam.png"
alt="drawing" width="900"/>

 Grounded SAM 概览。摘自原始仓库。

## 资源

以下是来自 Hugging Face 官方和社区（以 🌎 标识）的资源列表，可帮助您开始使用 Grounding DINO。如果您有兴趣提交资源以收录在此处，请随时发起 Pull Request，我们将进行审核！理想情况下，该资源应展示一些新内容，而不是重复现有资源。

- 有关使用 Grounding DINO 进行推理以及将其与 [SAM](sam) 结合的演示笔记本，可以在[此处](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/Grounding%20DINO)找到。🌎

## GroundingDinoImageProcessor[[transformers.GroundingDinoImageProcessor]]

#### transformers.GroundingDinoImageProcessor[[transformers.GroundingDinoImageProcessor]]

```python
transformers.GroundingDinoImageProcessor(**kwargs: *<class 'transformers.models.grounding_dino.image_processing_grounding_dino.GroundingDinoImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/image_processing_grounding_dino.py#L308)

**参数：**

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'shortest_edge' : 800, 'longest_edge': 1333}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 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*，默认为 `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.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 是否对图像进行居中裁剪。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

format (`str`, *kwargs*, *可选*，默认为 `AnnotationFormat.COCO_DETECTION`)：注释的数据格式。取值为 "coco_detection" 或 "coco_panoptic" 之一。

do_convert_annotations (`bool`, *kwargs*, *可选*，默认为 `True`)：控制是否将注释转换为 GROUNDING_DINO 模型所期望的格式。将边界框转换为 `(center_x, center_y, width, height)` 格式，且范围在 `[0, 1]` 内。可通过 `preprocess` 方法中的 `do_convert_annotations` 参数进行覆盖。

构建一个 GroundingDinoImageProcessor 图像处理器。

#### preprocess[[transformers.GroundingDinoImageProcessor.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = None, return_segmentation_masks: bool | None = None, masks_path: str | pathlib.Path | None = None, **kwargs: *<class 'transformers.models.grounding_dino.image_processing_grounding_dino.GroundingDinoImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/image_processing_grounding_dino.py#L563)

**参数：**

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

annotations (`AnnotationType` 或 `list[AnnotationType]`，*可选*)：根据应用于图像的填充进行转换的注释。

return_segmentation_masks (`bool`, *可选*, 默认为 `self.return_segmentation_masks`) : 是否返回分割掩码。

masks_path (`str` 或 `pathlib.Path`，*可选*)：包含分割掩码的目录路径。

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 为 int 时，是否在调整大小时默认使用正方形图像。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

format (`str`, *kwargs*, *可选*，默认为 `AnnotationFormat.COCO_DETECTION`)：注释的数据格式。取值为 "coco_detection" 或 "coco_panoptic" 之一。

do_convert_annotations (`bool`, *kwargs*, *可选*，默认为 `True`)：控制是否将注释转换为 GROUNDING_DINO 模型所期望的格式。将边界框转换为 `(center_x, center_y, width, height)` 格式，且范围在 `[0, 1]` 内。可通过 `preprocess` 方法中的 `do_convert_annotations` 参数进行覆盖。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

## GroundingDinoImageProcessorPil[[transformers.GroundingDinoImageProcessorPil]]

#### transformers.GroundingDinoImageProcessorPil[[transformers.GroundingDinoImageProcessorPil]]

```python
transformers.GroundingDinoImageProcessorPil(**kwargs: *<class 'transformers.models.grounding_dino.image_processing_pil_grounding_dino.GroundingDinoImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/image_processing_pil_grounding_dino.py#L300)

**参数：**

do_convert_rgb (`bool`, *kwargs*, *可选*) : 是否将图像转换为 RGB。

do_resize (`bool`, *kwargs*, *可选*, 默认为 `True`) : 是否调整图像大小。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `{'shortest_edge' : 800, 'longest_edge': 1333}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 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*，默认为 `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.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 是否对图像进行居中裁剪。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

format (`str`, *kwargs*, *可选*，默认为 `AnnotationFormat.COCO_DETECTION`)：注释的数据格式。取值为 "coco_detection" 或 "coco_panoptic" 之一。

do_convert_annotations (`bool`, *kwargs*, *可选*，默认为 `True`)：控制是否将注释转换为 GROUNDING_DINO 模型所期望的格式。将边界框转换为 `(center_x, center_y, width, height)` 格式，且范围在 `[0, 1]` 内。可通过 `preprocess` 方法中的 `do_convert_annotations` 参数进行覆盖。

构建一个 GroundingDinoImageProcessor 图像处理器。

#### preprocess[[transformers.GroundingDinoImageProcessorPil.preprocess]]

```python
preprocess(images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']], annotations: dict[str, int | str | list[dict]] | list[dict[str, int | str | list[dict]]] | None = None, return_segmentation_masks: bool | None = None, masks_path: str | pathlib.Path | None = None, **kwargs: *<class 'transformers.models.grounding_dino.image_processing_pil_grounding_dino.GroundingDinoImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/image_processing_pil_grounding_dino.py#L568)

**参数：**

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

annotations (`AnnotationType` 或 `list[AnnotationType]`，*可选*)：根据应用于图像的填充进行转换的注释。

return_segmentation_masks (`bool`, *可选*, 默认为 `self.return_segmentation_masks`) : 是否返回分割掩码。

masks_path (`str` 或 `pathlib.Path`，*可选*)：包含分割掩码的目录路径。

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 为 int 时，是否在调整大小时默认使用正方形图像。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

format (`str`, *kwargs*, *可选*，默认为 `AnnotationFormat.COCO_DETECTION`)：注释的数据格式。取值为 "coco_detection" 或 "coco_panoptic" 之一。

do_convert_annotations (`bool`, *kwargs*, *可选*，默认为 `True`)：控制是否将注释转换为 GROUNDING_DINO 模型所期望的格式。将边界框转换为 `(center_x, center_y, width, height)` 格式，且范围在 `[0, 1]` 内。可通过 `preprocess` 方法中的 `do_convert_annotations` 参数进行覆盖。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

#### post_process_object_detection[[transformers.GroundingDinoImageProcessorPil.post_process_object_detection]]

```python
post_process_object_detection(outputs: GroundingDinoObjectDetectionOutput, threshold: float = 0.1, target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/image_processing_pil_grounding_dino.py#L713)

**参数：**

outputs (`GroundingDinoObjectDetectionOutput`)：模型的原始输出。

threshold (`float`, *可选*，默认为 0.1)：用于保留目标检测预测结果的分数阈值。

target_sizes (`torch.Tensor` 或 `list[tuple[int, int]]`，*可选*)：形状为 `(batch_size, 2)` 的张量，或包含元组（`tuple[int, int]`）的列表，其中包含批处理中每张图片的目标尺寸 `(height, width)`。如果未设置，预测结果将不会被调整大小。

**返回：** `list[Dict]`

一个字典列表，每个字典包含以下键：
- ：图像上每个预测框的置信度分数。
- "labels": 模型在图像上预测的类别索引。
- "boxes": 图像边界框，格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。

将 [GroundingDinoForObjectDetection](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoForObjectDetection) 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最终边界框。

## GroundingDinoProcessor[[transformers.GroundingDinoProcessor]]

#### transformers.GroundingDinoProcessor[[transformers.GroundingDinoProcessor]]

```python
transformers.GroundingDinoProcessor(image_processor, tokenizer)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/processing_grounding_dino.py#L100)

**参数：**

image_processor (`GroundingDinoImageProcessor`)：图像处理器是必需的输入。

tokenizer (`BertTokenizer`)：分词器是必需的输入。

构建一个 GroundingDinoProcessor，它将图像处理器和分词器封装为单一处理器。

[GroundingDinoProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoProcessor) 提供了 [GroundingDinoImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoImageProcessor) 和 [BertTokenizer](/docs/transformers/v5.23.0/zh/model_doc/lxmert#transformers.BertTokenizer) 的所有功能。有关更多信息，请参阅 [~GroundingDinoImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoImageProcessor) 和 [~BertTokenizer](/docs/transformers/v5.23.0/zh/model_doc/lxmert#transformers.BertTokenizer)。

#### __调用__[[transformers.GroundingDinoProcessor.__call__]]

```python
__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: str | list[str] | list[list[str]] | None = None, videos: typing.Union[list['PIL.Image.Image'], numpy.ndarray, ForwardRef('torch.Tensor'), list[numpy.ndarray], list['torch.Tensor'], list[list['PIL.Image.Image']], list[list[numpy.ndarray]], list[list['torch.Tensor']], transformers.video_utils.URL, list[transformers.video_utils.URL], list[list[transformers.video_utils.URL]], transformers.video_utils.Path, list[transformers.video_utils.Path], list[list[transformers.video_utils.Path]], NoneType] = None, audio: typing.Union[numpy.ndarray, ForwardRef('torch.Tensor'), collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.processing_utils.ProcessingKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/processing_utils.py#L670)

**参数：**

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` 以避免与批量输入产生歧义。

videos (`Union[list[PIL.Image.Image], numpy.ndarray, torch.Tensor, list[numpy.ndarray], list[torch.Tensor], list[list[PIL.Image.Image]], list[list[numpy.ndarray]], list[list[torch.Tensor]], ~video_utils.URL, list[~video_utils.URL], list[list[~video_utils.URL]], ~video_utils.Path, list[~video_utils.Path], list[list[~video_utils.Path]]]`，*可选*)：要预处理的视频。期望输入单个视频或一批视频，其像素值范围为 0 到 255。如果传入的像素值在 0 到 1 之间，请设置 `do_rescale=False`。

audio (`Union[numpy.ndarray, torch.Tensor, collections.abc.Sequence[numpy.ndarray], collections.abc.Sequence[torch.Tensor]]`，*可选*)：要准备处理的音频或音频批次。每个音频可以是 NumPy 数组或 PyTorch 张量。对于 NumPy 数组/PyTorch 张量，每个音频的形状应为 (C, T)，其中 C 是通道数，T 是音频的采样长度。

return_mm_token_type_ids (`bool`, *kwargs*) : 是否返回多模态 token 类型 ID，以指示多模态占位符 token 的位置。

return_text_replacement_offsets (`bool`, *kwargs*) : 是否返回每个多模态占位符及其替换项的字符偏移量。

return_tensors (`str` 或 [TensorType](/docs/transformers/v5.23.0/zh/internal/file_utils#transformers.TensorType)，*可选*)：如果设置，将返回特定框架的张量。可接受的值为： - `'pt'`：返回 PyTorch `torch.Tensor` 对象。 - `'np'`：返回 NumPy `np.ndarray` 对象。

- ****kwargs** ([ProcessingKwargs](/docs/transformers/v5.23.0/zh/main_classes/processors#transformers.ProcessingKwargs), *可选*) : 针对每种模态（文本、图像、视频、音频）的额外处理选项。模型特定参数已在上方列出；有关支持参数的完整列表，请参阅 TypedDict 类。

#### post_process_grounded_object_detection[[transformers.GroundingDinoProcessor.post_process_grounded_object_detection]]

```python
post_process_grounded_object_detection(outputs: GroundingDinoObjectDetectionOutput, input_ids: transformers.utils.generic.TensorType | None = None, threshold: float = 0.25, text_threshold: float = 0.25, target_sizes: transformers.utils.generic.TensorType | list[tuple] | None = None, text_labels: list[list[str]] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/processing_grounding_dino.py#L130)

**参数：**

outputs (`GroundingDinoObjectDetectionOutput`)：模型的原始输出。

input_ids (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：输入文本的 token id。如果未提供，将从模型输出中获取。

threshold (`float`, *可选*，默认为 0.25)：用于根据置信度分数保留目标检测预测结果的阈值。

text_threshold (`float`, *可选*，默认为 0.25)：用于保留文本检测预测结果的分数阈值。

target_sizes (`torch.Tensor` 或 `list[tuple[int, int]]`，*可选*)：形状为 `(batch_size, 2)` 的张量，或包含元组（`tuple[int, int]`）的列表，其中包含批处理中每张图片的目标尺寸 `(height, width)`。如果未设置，预测结果将不会被调整大小。

text_labels (`list[list[str]]`, *可选*) : 要在每张图片上检测的候选标签列表。目前*尚未使用*，但零样本目标检测流水线的签名中要求包含此参数。文本标签实际上是从 `outputs` 中提供的 `input_ids` 张量中提取的。

**返回：** `list[Dict]`

一个字典列表，每个字典包含
- **scores**：检测到的对象的置信度分数张量
- **boxes**：格式为 [x0, y0, x1, y1] 的边界框张量
- **labels**：每个检测到的对象的文本标签列表（将在 v4.51.0 中替换为整数 ID）
- **text_labels**：检测到的对象的文本标签列表

将 [GroundingDinoForObjectDetection](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoForObjectDetection) 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的边界框，并获取相应的文本标签。

## GroundingDinoConfig[[transformers.GroundingDinoConfig]]

#### transformers.GroundingDinoConfig[[transformers.GroundingDinoConfig]]

```python
transformers.GroundingDinoConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, is_encoder_decoder: bool = True, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, text_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, num_queries: int = 900, encoder_layers: int = 6, encoder_ffn_dim: int = 2048, encoder_attention_heads: int = 8, decoder_layers: int = 6, decoder_ffn_dim: int = 2048, decoder_attention_heads: int = 8, activation_function: str = 'relu', d_model: int = 256, dropout: float | int = 0.1, attention_dropout: float | int = 0.0, activation_dropout: float | int = 0.0, auxiliary_loss: bool = False, position_embedding_type: str = 'sine', num_feature_levels: int = 4, encoder_n_points: int = 4, decoder_n_points: int = 4, two_stage: bool = True, class_cost: float = 1.0, bbox_cost: float = 5.0, giou_cost: float = 2.0, bbox_loss_coefficient: float = 5.0, giou_loss_coefficient: float = 2.0, focal_alpha: float = 0.25, disable_custom_kernels: bool = False, max_text_len: int = 256, text_enhancer_dropout: float | int = 0.0, fusion_droppath: float | int = 0.1, fusion_dropout: float | int = 0.0, embedding_init_target: bool = True, query_dim: int = 4, decoder_bbox_embed_share: bool = True, two_stage_bbox_embed_share: bool = False, positional_embedding_temperature: int = 20, init_std: float = 0.02, layer_norm_eps: float = 1e-05, tie_word_embeddings: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/configuration_grounding_dino.py#L28)

**参数：**

is_encoder_decoder (`bool`，*可选*，默认为 `True`)：模型是否用作编码器/解码器。

backbone_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：骨干模型的配置。

text_config (`Union[dict, ~configuration_utils.PreTrainedConfig]`，*可选*)：文本骨干网络的配置对象或字典。

num_queries (`int`, *可选*，默认为 900)：对象查询的数量，即检测槽位。这是 [GroundingDinoModel](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoModel) 在单张图像中可检测到的最大对象数量。

encoder_layers (`int`，*可选*，默认为 `6`)：Transformer 编码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

encoder_ffn_dim (`int`，*可选*，默认为 `2048`)：编码器中“中间”（通常称为前馈）层的维度。

encoder_attention_heads (`int`，*可选*，默认为 `8`)：Transformer 编码器中每个注意力层的注意力头数量。

decoder_layers (`int`，*可选*，默认为 `6`)：Transformer 解码器中的隐藏层数。如果未设置，将使用与 `num_layers` 相同的值。

decoder_ffn_dim (`int`，*可选*，默认为 `2048`)：解码器中“中间”（通常称为前馈）层的维度。

decoder_attention_heads (`int`，*可选*，默认为 `8`)：Transformer 解码器中每个注意力层的注意力头数量。

activation_function (`str`，*可选*，默认为 `relu`)：解码器中的非线性激活函数（函数或字符串）。例如，`"gelu"`、`"relu"`、`"silu"` 等。

d_model (`int`，*可选*，默认为 `256`)：编码器层和池化层的大小。

dropout (`Union[float, int]`，*可选*，默认为 `0.1`)：所有 dropout 层的比率。

attention_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：注意力概率的 dropout 比率。

activation_dropout (`Union[float, int]`，*可选*，默认值为 `0.0`)：全连接层内部激活值的 dropout 比率。

auxiliary_loss (`bool`，*可选*，默认为 `False`)：是否使用辅助解码损失（即每个解码器层的损失）。

position_embedding_type (`str`，*可选*，默认为 `"sine"`)：用于叠加在图像特征之上的位置嵌入类型。取值为 `"sine"` 或 `"learned"` 之一。

num_feature_levels (`int`，*可选*，默认为 4)：输入特征层级的数量。

encoder_n_points (`int`，*可选*，默认为 4)：编码器中每个注意力头在每个特征层级中采样的键数量。

decoder_n_points (`int`，*可选*，默认为 4)：解码器中每个注意力头在每个特征层级中采样的键数量。

two_stage (`bool`, *可选*, 默认为 `True`) : 是否应用两阶段可变形 DETR，其中区域提案也由 Grounding DINO 的变体生成，并进一步输入解码器以进行迭代边界框细化。

class_cost (`float`, *可选*, 默认为 `1.0`) : 匈牙利匹配代价中分类误差的相对权重。

bbox_cost (`float`, *可选*, 默认为 `5.0`) : 匈牙利匹配代价中 L1 边界框误差的相对权重。

giou_cost (`float`, *可选*, 默认为 `2.0`) : 匈牙利匹配代价中广义 IoU 损失的相对权重。

bbox_loss_coefficient (`float`, *可选*，默认为 `5.0`)：全景分割损失中 L1 边界框损失的相对权重。

giou_loss_coefficient (`float`, *可选*，默认为 `2.0`)：全景分割损失中广义 IoU 损失的相对权重。

focal_alpha (`float`, *可选*, 默认为 `0.25`) : 焦点损失中的 Alpha 参数。

disable_custom_kernels (`bool`，*可选*，默认为 `False`)：禁用自定义 CUDA 和 CPU 内核。此选项对于 ONNX 导出是必需的，因为 PyTorch ONNX 导出不支持自定义内核。

max_text_len (`int`，*可选*，默认为 256)：文本输入的最大长度。

text_enhancer_dropout (`float`, *可选*, 默认值为 0.0) : 文本增强器的 dropout 比率。

fusion_droppath (`float`, *可选*，默认为 0.1)：融合模块的 droppath 比率。

fusion_dropout (`float`, *可选*，默认为 0.0)：融合模块的 dropout 比率。

embedding_init_target (`bool`，*可选*，默认为 `True`)：是否使用 Embedding 权重初始化目标。

query_dim (`int`，*可选*，默认为 4)：查询向量的维度。

decoder_bbox_embed_share (`bool`, *可选*, 默认为 `True`) : 是否在所有解码器层中共享边界框回归头。

two_stage_bbox_embed_share (`bool`, *可选*, 默认为 `False`) : 是否在两阶段边界框生成器和区域建议生成之间共享边界框嵌入。

positional_embedding_temperature (`float`, *可选*，默认为 20)：与视觉骨干网络一起使用的正弦位置嵌入的温度。

init_std (`float`，*可选*，默认值为 `0.02`)：用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

layer_norm_eps (`float`，*可选*，默认为 `1e-05`)：层归一化层所使用的 epsilon。

tie_word_embeddings (`bool`，*可选*，默认为 `True`)：是否根据模型的 `tied_weights_keys` 映射来绑定权重嵌入。

这是用于存储 Grounding Dino 模型配置的类。它根据指定的参数实例化 Grounding Dino 模型，并定义模型架构。使用默认值实例化配置将生成与 [IDEA-Research/grounding-dino-tiny](https://huggingface.co/IDEA-Research/grounding-dino-tiny) 类似的配置。

配置对象继承自 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig)，可用于控制模型输出。有关更多信息，请参阅 [PreTrainedConfig](/docs/transformers/v5.23.0/zh/main_classes/configuration#transformers.PreTrainedConfig) 的文档。

示例：

```python
>>> from transformers import GroundingDinoConfig, GroundingDinoModel

>>> # Initializing a Grounding DINO IDEA-Research/grounding-dino-tiny style configuration
>>> configuration = GroundingDinoConfig()

>>> # Initializing a model (with random weights) from the IDEA-Research/grounding-dino-tiny style configuration
>>> model = GroundingDinoModel(configuration)

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

## GroundingDinoModel[[transformers.GroundingDinoModel]]

#### transformers.GroundingDinoModel[[transformers.GroundingDinoModel]]

```python
transformers.GroundingDinoModel(config: GroundingDinoConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/modeling_grounding_dino.py#L1869)

**参数：**

config ([GroundingDinoConfig](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

原始的 Grounding DINO 模型（由骨干网络和编码器-解码器 Transformer 组成），其顶部没有特定的输出头，直接输出原始的隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.GroundingDinoModel.forward]]

```python
forward(pixel_values: Tensor, input_ids: Tensor, token_type_ids: typing.Optional[torch.Tensor] = None, attention_mask: typing.Optional[torch.Tensor] = None, pixel_mask: typing.Optional[torch.Tensor] = None, encoder_outputs = None, output_attentions = None, output_hidden_states = None, return_dict = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/modeling_grounding_dino.py#L2015)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [GroundingDinoImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoImageProcessor) 获取像素值。有关详细信息，请参阅 [GroundingDinoImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[GroundingDinoProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoProcessor) 使用 [GroundingDinoImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoImageProcessor) 来处理图像）。

input_ids (`torch.LongTensor`，形状为 `(batch_size, text_sequence_length)`)：输入序列词元在词汇表中的索引。如果您提供了填充，默认情况下将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [BertTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。

token_type_ids (`torch.LongTensor`，形状为 `(batch_size, text_sequence_length)`，*可选*)：用于指示输入中第一和第二部分的段标记索引。索引选自 `[0, 1]`：0 对应 `sentence A` 标记，1 对应 `sentence B` 标记 [什么是 token type IDs？](../glossary#token-type-ids)

attention_mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值取自 `[0, 1]`： - 1 表示**未掩码**的标记， - 0 表示**已掩码**的标记。 [什么是注意力掩码？](../glossary#attention-mask)

pixel_mask (`torch.Tensor`，形状为 `(batch_size, height, width)`，*可选*)：用于避免对填充像素值执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 1 表示真实像素（即 **未掩码**）， - 0 表示填充像素（即 **已掩码**）。 [什么是注意力掩码？](../glossary#attention-mask)

encoder_outputs (``) : Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`) `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`，*optional*) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。

output_attentions (``) : Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail.

output_hidden_states (``) : Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail.

return_dict (``) : 是否返回 [ModelOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

**返回：** `GroundingDinoModelOutput` 或 `tuple(torch.Tensor)`

`GroundingDinoModelOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[GroundingDinoConfig](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoConfig)）和输入。

[GroundingDinoModel](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **last_hidden_state**（形状为 `(batch_size, num_queries, hidden_size)` 的 `torch.Tensor`）-- 模型解码器最后一层输出的隐藏状态序列。
- **init_reference_points**（形状为 `(batch_size, num_queries, 4)` 的 `torch.Tensor`）-- 通过 Transformer 解码器发送的初始参考点。
- **intermediate_hidden_states**（形状为 `(batch_size, config.decoder_layers, num_queries, hidden_size)` 的 `torch.Tensor`）-- 堆叠的中间隐藏状态（解码器每一层的输出）。
- **intermediate_reference_points**（形状为 `(batch_size, config.decoder_layers, num_queries, 4)` 的 `torch.Tensor`）-- 堆叠的中间参考点（解码器每一层的参考点）。
- **decoder_hidden_states** (`tuple[torch.Tensor]`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, sequence_length, hidden_size)`。

  解码器在每一层输出处的隐藏状态，以及初始嵌入输出。
- **decoder_attentions** (`tuple[tuple[torch.Tensor]]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器在注意力 softmax 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **encoder_last_hidden_state_vision**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型编码器最后一层输出的隐藏状态序列。
- **encoder_last_hidden_state_text** (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*) -- 模型编码器最后一层输出的隐藏状态序列。
- **encoder_vision_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含视觉嵌入的输出以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。视觉编码器在每一层输出处的隐藏状态，以及初始嵌入的输出。
- **encoder_text_hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含文本嵌入的输出以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。文本编码器在每一层输出处的隐藏状态，以及初始嵌入输出。
- **encoder_attentions** (`tuple(tuple(torch.Tensor))`，*可选*，在传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 由 `torch.Tensor` 组成的元组（每层注意力对应一个元组），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。注意力 softmax 之后的注意力权重，用于计算文本-视觉注意力、视觉-文本注意力、文本增强器（自注意力）以及多尺度可变形注意力头中的加权平均值。注意力 softmax，用于计算双向注意力头中的加权平均值。
- **enc_outputs_class** (`torch.Tensor`，形状为 `(batch_size, sequence_length, config.num_labels)`，*可选*，当 `config.two_stage=True` 时返回) -- 预测的边界框分数，其中得分最高的 `config.num_queries` 个边界框将在第一阶段被选为区域建议。这是边界框二分类（即前景和背景）的输出。
- **enc_outputs_coord_logits** (`torch.Tensor`，形状为 `(batch_size, sequence_length, 4)`，*可选*，当 `config.two_stage=True` 时返回) -- 第一阶段中预测的边界框坐标的 logits。
- **encoder_logits**（形状为 `(batch_size, sequence_length, config.num_labels)` 的 `torch.Tensor`，*可选*，当 `config.two_stage=True` 时返回）-- 第一阶段中得分最高的 `config.num_queries` 个边界框的 logits。
- **encoder_pred_boxes**（形状为 `(batch_size, sequence_length, 4)` 的 `torch.Tensor`，*可选*，当 `config.two_stage=True` 时返回） -- 第一阶段中得分最高的 `config.num_queries` 个边界框的坐标。

示例：

```python
>>> from transformers import AutoProcessor, AutoModel
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> text = "a cat."

>>> processor = AutoProcessor.from_pretrained("IDEA-Research/grounding-dino-tiny")
>>> model = AutoModel.from_pretrained("IDEA-Research/grounding-dino-tiny")

>>> inputs = processor(images=image, text=text, return_tensors="pt")
>>> outputs = model(**inputs)

>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 900, 256]
```

## GroundingDinoForObjectDetection[[transformers.GroundingDinoForObjectDetection]]

#### transformers.GroundingDinoForObjectDetection[[transformers.GroundingDinoForObjectDetection]]

```python
transformers.GroundingDinoForObjectDetection(config: GroundingDinoConfig)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/modeling_grounding_dino.py#L2385)

**参数：**

config ([GroundingDinoConfig](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoConfig))：模型配置类，包含模型的所有参数。通过配置文件进行初始化时，不会加载与模型关联的权重，仅加载配置。请查看 [from_pretrained()](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained) 方法以加载模型权重。

Grounding DINO 模型（由骨干网络和编码器-解码器 Transformer 组成），顶部配有目标检测头，用于 COCO 检测等任务。

该模型继承自 [PreTrainedModel](/docs/transformers/v5.23.0/zh/main_classes/model#transformers.PreTrainedModel)。请查阅父类文档，了解该库为所有模型实现的通用方法（例如下载或保存、调整输入嵌入大小、剪枝头等）。

该模型也是 PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) 的子类。请将其作为常规的 PyTorch Module 使用，有关通用用法和行为的所有事项，请参阅 PyTorch 文档。

#### forward[[transformers.GroundingDinoForObjectDetection.forward]]

```python
forward(pixel_values: Tensor, input_ids: LongTensor, token_type_ids: typing.Optional[torch.LongTensor] = None, attention_mask: typing.Optional[torch.LongTensor] = None, pixel_mask: typing.Optional[torch.BoolTensor] = None, encoder_outputs: transformers.models.grounding_dino.modeling_grounding_dino.GroundingDinoEncoderOutput | tuple | None = None, output_attentions: bool | None = None, output_hidden_states: bool | None = None, return_dict: bool | None = None, labels: list[dict[str, typing.Union[torch.LongTensor, torch.Tensor]]] | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/v5.23.0/src/transformers/models/grounding_dino/modeling_grounding_dino.py#L2426)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [GroundingDinoImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoImageProcessor) 获取像素值。有关详细信息，请参阅 [GroundingDinoImageProcessor.__call__()](/docs/transformers/v5.23.0/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（[GroundingDinoProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoProcessor) 使用 [GroundingDinoImageProcessor](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoImageProcessor) 来处理图像）。

input_ids (`torch.LongTensor`，形状为 `(batch_size, text_sequence_length)`)：输入序列词元在词汇表中的索引。如果您提供了填充，默认情况下将被忽略。可以使用 [AutoTokenizer](/docs/transformers/v5.23.0/zh/model_doc/auto#transformers.AutoTokenizer) 获取索引。有关详细信息，请参阅 [BertTokenizer.__call__()](/docs/transformers/v5.23.0/zh/internal/tokenization_utils#transformers.PreTrainedTokenizerBase.__call__)。

token_type_ids (`torch.LongTensor`，形状为 `(batch_size, text_sequence_length)`，*可选*)：用于指示输入中第一和第二部分的段标记索引。索引选自 `[0, 1]`：0 对应 `sentence A` 标记，1 对应 `sentence B` 标记 [什么是 token type IDs？](../glossary#token-type-ids)

attention_mask (`torch.LongTensor`，形状为 `(batch_size, sequence_length)`，*可选*)：用于避免对填充（padding）标记索引执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 对于**未掩码**的标记，值为 1； - 对于**已掩码**的标记，值为 0。 [什么是注意力掩码？](../glossary#attention-mask)

pixel_mask (`torch.BoolTensor`，形状为 `(batch_size, height, width)`，*可选*)：用于避免对填充像素值执行注意力机制的掩码。掩码值选自 `[0, 1]`： - 1 表示真实像素（即 **未掩码**）， - 0 表示填充像素（即 **已掩码**）。 [什么是注意力掩码？](../glossary#attention-mask)

encoder_outputs (`Union[~models.grounding_dino.modeling_grounding_dino.GroundingDinoEncoderOutput, tuple]`, *可选*) : 元组由 (`last_hidden_state`, *可选*: `hidden_states`, *可选*: `attentions`) `last_hidden_state` 形状为 `(batch_size, sequence_length, hidden_size)`, *可选*) 组成，是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力中。

output_attentions (`bool`, *可选*) : 是否返回所有注意力层的注意力张量。有关更多详细信息，请参阅返回张量中的 `attentions`。

output_hidden_states (`bool`, *可选*) : 是否返回所有层的隐藏状态。有关更多详细信息，请参阅返回张量中的 `hidden_states`。

return_dict (`bool`, *可选*) : 是否返回 [ModelOutput](/docs/transformers/v5.23.0/zh/main_classes/output#transformers.utils.ModelOutput) 而不是普通元组。

labels (`list[Dict]`，长度为 `(batch_size,)`，*可选*) : 用于计算二分匹配损失的标签。一个字典列表，每个字典至少包含以下 2 个键：'class_labels' 和 'boxes'（分别表示批次中某张图像的分类标签和边界框）。分类标签本身应是一个长度为 `(number of bounding boxes in the image,)` 的 `torch.LongTensor`，边界框应是一个形状为 `(number of bounding boxes in the image, 4)` 的 `torch.Tensor`。

[GroundingDinoForObjectDetection](/docs/transformers/v5.23.0/zh/model_doc/grounding-dino#transformers.GroundingDinoForObjectDetection) 的 forward 方法重写了 `__call__` 特殊方法。

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

示例：

```python
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> import torch
>>> from PIL import Image
>>> from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection

>>> model_id = "IDEA-Research/grounding-dino-tiny"
>>> device = "cuda"

>>> processor = AutoProcessor.from_pretrained(model_id)
>>> model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(device)

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))
>>> # Check for cats and remote controls
>>> text_labels = [["a cat", "a remote control"]]

>>> inputs = processor(images=image, text=text_labels, return_tensors="pt").to(device)
>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> results = processor.post_process_grounded_object_detection(
...     outputs,
...     threshold=0.4,
...     text_threshold=0.3,
...     target_sizes=[(image.height, image.width)]
... )
>>> # Retrieve the first image result
>>> result = results[0]
>>> for box, score, text_label in zip(result["boxes"], result["scores"], result["text_labels"]):
...     box = [round(x, 2) for x in box.tolist()]
...     print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected a cat with confidence 0.479 at location [344.7, 23.11, 637.18, 374.28]
Detected a cat with confidence 0.438 at location [12.27, 51.91, 316.86, 472.44]
Detected a remote control with confidence 0.478 at location [38.57, 70.0, 176.78, 118.18]
```

