Transformers 文档
Grounding DINO
并获得增强的文档体验
开始使用
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 中提出。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 零样本基准上以平均 26.1 AP 的成绩创下新纪录。

该模型由 EduardoPacheco 和 nielsr 贡献。原始代码可以在这里找到。
使用技巧
- 可以使用 GroundingDinoProcessor 为模型准备图文对。
- 要在文本中分隔类别,请使用句点,例如“a cat. a dog.”。
- 当使用多个类别时(例如
"a cat. a dog."
),请使用 GroundingDinoProcessor 中的post_process_grounded_object_detection
对输出进行后处理。因为,从post_process_object_detection
返回的标签代表了模型维度中 prob > threshold 的索引。
以下是如何使用该模型进行零样本目标检测的方法:
>>> import requests
>>> 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)
>>> 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(device)
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> results = processor.post_process_grounded_object_detection(
... outputs,
... inputs.input_ids,
... box_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
正如 Grounded SAM: Assembling Open-World Models for Diverse Visual Tasks 中介绍的那样,可以将 Grounding DINO 与 Segment Anything 模型结合,用于基于文本的掩码生成。您可以参考这个演示笔记本 🌍 了解详情。

资源
Hugging Face 官方和社区(由 🌍 表示)提供的资源列表,帮助您开始使用 Grounding DINO。如果您有兴趣提交要包含在此处的资源,请随时发起 Pull Request,我们会进行审核!该资源最好能展示一些新内容,而不是重复现有资源。
GroundingDinoImageProcessor
class transformers.GroundingDinoImageProcessor
< 来源 >( format: typing.Union[str, transformers.models.grounding_dino.image_processing_grounding_dino.AnnotationFormat] = <AnnotationFormat.COCO_DETECTION: 'coco_detection'> do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_convert_annotations: typing.Optional[bool] = None do_pad: bool = True pad_size: typing.Optional[dict[str, int]] = None **kwargs )
参数
- format (
str
, 可选, 默认为AnnotationFormat.COCO_DETECTION
) — 标注的数据格式。可以是 “coco_detection” 或 “coco_panoptic”。 - do_resize (
bool
, 可选, 默认为True
) — 控制是否将图像的(高,宽)维度调整为指定的size
。可以通过preprocess
方法中的do_resize
参数覆盖。 - size (
dict[str, int]
可选, 默认为{"shortest_edge" -- 800, "longest_edge": 1333}
): 调整大小后图像的 `(height, width)` 尺寸。可以通过 `preprocess` 方法中的 `size` 参数覆盖。可用选项有:- `{"height": int, "width": int}`:图像将被调整为精确的 `(height, width)` 尺寸。不保持宽高比。
- `{"shortest_edge": int, "longest_edge": int}`:图像将在保持宽高比的情况下调整大小,使最短边小于或等于 `shortest_edge`,最长边小于或等于 `longest_edge`。
- `{"max_height": int, "max_width": int}`:图像将在保持宽高比的情况下调整大小,使高度小于或等于 `max_height`,宽度小于或等于 `max_width`。
- resample (
PILImageResampling
, 可选, 默认为Resampling.BILINEAR
) — 如果调整图像大小,使用的重采样过滤器。 - do_rescale (
bool
, 可选, 默认为True
) — 控制是否按指定的比例rescale_factor
重新缩放图像。可以通过preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果重新缩放图像,使用的缩放因子。可以通过preprocess
方法中的rescale_factor
参数覆盖。控制是否对图像进行归一化。可以通过preprocess
方法中的do_normalize
参数覆盖。 - do_normalize (
bool
, 可选, 默认为True
) — 是否对图像进行归一化。可以通过preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或list[float]
, 可选, 默认为IMAGENET_DEFAULT_MEAN
) — 对图像进行归一化时使用的均值。可以是一个单一值,也可以是一个列表,每个通道一个值。可以通过preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或list[float]
, 可选, 默认为IMAGENET_DEFAULT_STD
) — 对图像进行归一化时使用的标准差值。可以是一个单一值,也可以是一个列表,每个通道一个值。可以通过preprocess
方法中的image_std
参数覆盖。 - do_convert_annotations (
bool
, 可选, 默认为True
) — 控制是否将标注转换为 DETR 模型期望的格式。将边界框转换为 `(center_x, center_y, width, height)` 格式,并在 `[0, 1]` 范围内。可以通过 `preprocess` 方法中的 `do_convert_annotations` 参数覆盖。 - do_pad (
bool
, 可选, 默认为True
) — 控制是否对图像进行填充。可以通过preprocess
方法中的do_pad
参数覆盖。如果为True
,则会在图像的底部和右侧用零填充。如果提供了pad_size
,图像将被填充到指定尺寸。否则,图像将被填充到批次中的最大高度和宽度。 - pad_size (
dict[str, int]
, 可选) — 图像填充到的尺寸 `{"height": int, "width" int}`。必须大于预处理时提供的任何图像尺寸。如果未提供 `pad_size`,图像将被填充到批次中的最大高度和宽度。
构建一个 Grounding DINO 图像处理器。
preprocess
< 来源 >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: typing.Union[dict[str, typing.Union[int, str, list[dict]]], list[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None return_segmentation_masks: typing.Optional[bool] = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Union[int, float, NoneType] = None do_normalize: typing.Optional[bool] = None do_convert_annotations: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_pad: typing.Optional[bool] = None format: typing.Union[str, transformers.models.grounding_dino.image_processing_grounding_dino.AnnotationFormat, NoneType] = None return_tensors: typing.Union[transformers.utils.generic.TensorType, str, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None pad_size: typing.Optional[dict[str, int]] = None **kwargs )
参数
- images (
ImageInput
) — 待预处理的图像或图像批次。期望是像素值范围在 0 到 255 之间的单个或批量图像。如果传入像素值在 0 到 1 之间的图像,请设置 `do_rescale=False`。 - annotations (
AnnotationType
或list[AnnotationType]
, 可选) — 与图像或图像批次相关联的标注列表。如果标注用于目标检测,标注应为一个字典,包含以下键:- “image_id” (
int
):图像 ID。 - “annotations” (
list[Dict]
):图像的标注列表。每个标注应为一个字典。一张图像可以没有标注,此时列表应为空。如果标注用于分割,标注应为一个字典,包含以下键: - “image_id” (
int
):图像 ID。 - “segments_info” (
list[Dict]
):图像的分割信息列表。每个分割信息应为一个字典。一张图像可以没有分割信息,此时列表应为空。 - “file_name” (
str
):图像的文件名。
- “image_id” (
- return_segmentation_masks (
bool
, 可选, 默认为 self.return_segmentation_masks) — 是否返回分割掩码。 - masks_path (
str
或pathlib.Path
, 可选) — 包含分割掩码的目录路径。 - do_resize (
bool
, 可选, 默认为 self.do_resize) — 是否调整图像大小。 - size (
dict[str, int]
, 可选, 默认为 self.size) — 调整大小后图像的 `(height, width)` 尺寸。可用选项有:- `{"height": int, "width": int}`:图像将被调整为精确的 `(height, width)` 尺寸。不保持宽高比。
- `{"shortest_edge": int, "longest_edge": int}`:图像将在保持宽高比的情况下调整大小,使最短边小于或等于 `shortest_edge`,最长边小于或等于 `longest_edge`。
- `{"max_height": int, "max_width": int}`:图像将在保持宽高比的情况下调整大小,使高度小于或等于 `max_height`,宽度小于或等于 `max_width`。
- resample (
PILImageResampling
, 可选, 默认为 self.resample) — 调整图像大小时使用的重采样过滤器。 - do_rescale (
bool
, 可选, 默认为 self.do_rescale) — 是否重新缩放图像。 - rescale_factor (
float
, 可选, 默认为 self.rescale_factor) — 重新缩放图像时使用的缩放因子。 - do_normalize (
bool
, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化。 - do_convert_annotations (
bool
, 可选, 默认为 self.do_convert_annotations) — 是否将标注转换为模型期望的格式。将边界框从 `(top_left_x, top_left_y, width, height)` 格式转换为 `(center_x, center_y, width, height)` 格式,并使用相对坐标。 - image_mean (
float
或list[float]
, 可选, 默认为 self.image_mean) — 对图像进行归一化时使用的均值。 - image_std (
float
或list[float]
, 可选, 默认为 self.image_std) — 对图像进行归一化时使用的标准差。 - do_pad (
bool
, 可选, 默认为 self.do_pad) — 是否对图像进行填充。如果为 `True`,则会在图像的底部和右侧用零填充。如果提供了 `pad_size`,图像将被填充到指定尺寸。否则,图像将被填充到批次中的最大高度和宽度。 - format (
str
或AnnotationFormat
, 可选, 默认为 self.format) — 标注的格式。 - return_tensors (
str
或TensorType
, 可选, 默认为 self.return_tensors) — 返回的张量类型。如果为None
,将返回图像列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
- pad_size (
dict[str, int]
, 可选) — 将图像填充到的尺寸{"height": int, "width" int}
。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size
,图像将被填充到批处理中最大的高度和宽度。
预处理图像或图像批次,以便模型可以使用。
GroundingDinoImageProcessorFast
class transformers.GroundingDinoImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.models.grounding_dino.image_processing_grounding_dino_fast.GroundingDinoFastImageProcessorKwargs] )
构建一个快速的 Grounding Dino 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] annotations: typing.Union[dict[str, typing.Union[int, str, list[dict]]], list[dict[str, typing.Union[int, str, list[dict]]]], NoneType] = None masks_path: typing.Union[str, pathlib.Path, NoneType] = None **kwargs: typing_extensions.Unpack[transformers.models.grounding_dino.image_processing_grounding_dino_fast.GroundingDinoFastImageProcessorKwargs] ) → <class 'transformers.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
。 - annotations (
AnnotationType
或list[AnnotationType]
, 可选) — 与图像或图像批次相关联的标注列表。如果标注用于目标检测,标注应为一个字典,包含以下键:- “image_id” (
int
):图像 ID。 - “annotations” (
list[Dict]
):图像的标注列表。每个标注应为一个字典。一张图像可以没有标注,此时列表应为空。如果标注用于分割,标注应为一个字典,包含以下键: - “image_id” (
int
):图像 ID。 - “segments_info” (
list[Dict]
):图像的分割信息列表。每个分割信息应为一个字典。一张图像可以没有分割信息,此时列表应为空。 - “file_name” (
str
):图像的文件名。
- “image_id” (
- masks_path (
str
或pathlib.Path
, 可选) — 包含分割掩码的目录路径。 - do_resize (
bool
, 可选) — 是否调整图像大小。 - size (
dict[str, int]
, 可选) — 描述模型最大输入尺寸。 - default_to_square (
bool
, 可选) — 当 size 为整数时,调整大小时是否默认为正方形图像。 - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — 如果调整图像大小,使用的重采样滤波器。可以是PILImageResampling
枚举之一。仅在do_resize
设置为True
时有效。 - do_center_crop (
bool
, 可选) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, 可选) — 应用center_crop
后输出图像的尺寸。 - do_rescale (
bool
, 可选) — 是否对图像进行缩放。 - rescale_factor (
Union[int, float, NoneType]
) — 如果do_rescale
设置为True
,用于缩放图像的缩放因子。 - do_normalize (
bool
, 可选) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], NoneType]
) — 用于归一化的图像均值。仅在do_normalize
设置为True
时有效。 - image_std (
Union[float, list[float], NoneType]
) — 用于归一化的图像标准差。仅在do_normalize
设置为True
时有效。 - do_convert_rgb (
bool
, 可选) — 是否将图像转换为 RGB。 - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
~image_utils.ChannelDimension
, 可选) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]
) — 输入图像的通道维度格式。如果未设置,将从输入图像中推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
- device (
torch.device
, 可选) — 处理图像的设备。如果未设置,将从输入图像中推断设备。 - disable_grouping (
bool
, 可选) — 是否禁用按尺寸对图像进行分组,以便单独处理而不是按批处理。如果为 None,则在图像位于 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,详见:https://github.com/huggingface/transformers/pull/38157 - format (
str
, 可选, 默认为AnnotationFormat.COCO_DETECTION
) — 标注的数据格式。可以是“coco_detection”或“coco_panoptic”之一。 - do_convert_annotations (
bool
, 可选, 默认为True
) — 控制是否将标注转换为 GROUNDING_DINO 模型期望的格式。将边界框转换为(center_x, center_y, width, height)
格式,且范围在[0, 1]
内。可以被preprocess
方法中的do_convert_annotations
参数覆盖。 - do_pad (
bool
, 可选, 默认为True
) — 控制是否填充图像。可以被preprocess
方法中的do_pad
参数覆盖。如果为True
,将使用零值对图像的底部和右侧进行填充。如果提供了pad_size
,图像将被填充到指定尺寸。否则,图像将被填充到批处理中的最大高度和宽度。 - pad_size (
dict[str, int]
, 可选) — 将图像填充到的尺寸{"height": int, "width" int}
。必须大于为预处理提供的任何图像尺寸。如果未提供pad_size
,图像将被填充到批处理中最大的高度和宽度。 - return_segmentation_masks (
bool
, 可选, 默认为False
) — 是否返回分割掩码。
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。
post_process_object_detection
< source >( outputs: GroundingDinoObjectDetectionOutput threshold: float = 0.1 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None ) → list[Dict]
参数
- outputs (
GroundingDinoObjectDetectionOutput
) — 模型的原始输出。 - threshold (
float
, 可选, 默认为 0.1) — 用于保留目标检测预测结果的分数阈值。 - target_sizes (
torch.Tensor
或list[tuple[int, int]]
, 可选) — 形状为(batch_size, 2)
的张量或元组列表 (tuple[int, int]
),包含批处理中每张图像的目标尺寸(height, width)
。如果未设置,预测结果将不会被调整大小。
返回
list[Dict]
一个字典列表,每个字典包含以下键:
- “scores”:图像上每个预测框的置信度分数。
- “labels”:模型在图像上预测的类别索引。
- “boxes”:图像边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
将 GroundingDinoForObjectDetection 的原始输出转换为最终的边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)。
GroundingDinoProcessor
class transformers.GroundingDinoProcessor
< source >( image_processor tokenizer )
参数
- image_processor (
GroundingDinoImageProcessor
) — GroundingDinoImageProcessor 的一个实例。图像处理器是必需的输入。 - tokenizer (
AutoTokenizer
) — [‘PreTrainedTokenizer`] 的一个实例。分词器是必需的输入。
构建一个 Grounding DINO 处理器,将 Deformable DETR 图像处理器和 BERT 分词器封装成一个单一的处理器。
GroundingDinoProcessor 提供了 GroundingDinoImageProcessor 和 AutoTokenizer 的所有功能。更多信息请参见 __call__()
和 decode()
的文档字符串。
post_process_grounded_object_detection
< source >( outputs: GroundingDinoObjectDetectionOutput input_ids: typing.Optional[transformers.utils.generic.TensorType] = None threshold: float = 0.25 text_threshold: float = 0.25 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None text_labels: typing.Optional[list[list[str]]] = None ) → list[Dict]
参数
- 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 的原始输出转换为最终的边界框,格式为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y),并获取相关的文本标签。
GroundingDinoConfig
class transformers.GroundingDinoConfig
< source >( backbone_config = None backbone = None use_pretrained_backbone = False use_timm_backbone = False backbone_kwargs = None text_config = None num_queries = 900 encoder_layers = 6 encoder_ffn_dim = 2048 encoder_attention_heads = 8 decoder_layers = 6 decoder_ffn_dim = 2048 decoder_attention_heads = 8 is_encoder_decoder = True activation_function = 'relu' d_model = 256 dropout = 0.1 attention_dropout = 0.0 activation_dropout = 0.0 auxiliary_loss = False position_embedding_type = 'sine' num_feature_levels = 4 encoder_n_points = 4 decoder_n_points = 4 two_stage = True class_cost = 1.0 bbox_cost = 5.0 giou_cost = 2.0 bbox_loss_coefficient = 5.0 giou_loss_coefficient = 2.0 focal_alpha = 0.25 disable_custom_kernels = False max_text_len = 256 text_enhancer_dropout = 0.0 fusion_droppath = 0.1 fusion_dropout = 0.0 embedding_init_target = True query_dim = 4 decoder_bbox_embed_share = True two_stage_bbox_embed_share = False positional_embedding_temperature = 20 init_std = 0.02 layer_norm_eps = 1e-05 **kwargs )
参数
- backbone_config (
PretrainedConfig
或dict
, 可选, 默认为ResNetConfig()
) — 主干模型的配置。 - backbone (
str
, 可选) — 当backbone_config
为None
时使用的主干名称。如果use_pretrained_backbone
为True
,将从 timm 或 transformers 库加载相应的预训练权重。如果use_pretrained_backbone
为False
,将加载主干的配置并用其初始化具有随机权重的主干。 - use_pretrained_backbone (
bool
, 可选, 默认为False
) — 是否为主干使用预训练权重。 - use_timm_backbone (
bool
, optional, 默认为False
) — 是否从 timm 库加载backbone
。如果为False
,则从 transformers 库加载主干网络。 - backbone_kwargs (
dict
, optional) — 从检查点加载时要传递给 AutoBackbone 的关键字参数,例如{'out_indices': (0, 1, 2, 3)}
。如果设置了backbone_config
,则不能指定此参数。 - text_config (
Union[AutoConfig, dict]
, optional, 默认为BertConfig
) — 文本主干网络的配置对象或字典。 - num_queries (
int
, optional, 默认为 900) — 对象查询的数量,即检测槽的数量。这是 GroundingDinoModel 在单张图片中可以检测的最大对象数量。 - encoder_layers (
int
, optional, 默认为 6) — 编码器层数。 - encoder_ffn_dim (
int
, optional, 默认为 2048) — 编码器中“中间”(通常称为前馈)层的维度。 - encoder_attention_heads (
int
, optional, 默认为 8) — Transformer 编码器中每个注意力层的注意力头数量。 - decoder_layers (
int
, optional, 默认为 6) — 解码器层数。 - decoder_ffn_dim (
int
, optional, 默认为 2048) — 解码器中“中间”(通常称为前馈)层的维度。 - decoder_attention_heads (
int
, optional, 默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。 - is_encoder_decoder (
bool
, optional, 默认为True
) — 模型是否用作编码器/解码器。 - activation_function (
str
或function
, optional, 默认为"relu"
) — 编码器和池化层中的非线性激活函数(函数或字符串)。如果为字符串,支持"gelu"
、"relu"
、"silu"
和"gelu_new"
。 - d_model (
int
, optional, 默认为 256) — 层的维度。 - dropout (
float
, optional, 默认为 0.1) — 嵌入层、编码器和池化层中所有全连接层的丢弃概率。 - attention_dropout (
float
, optional, 默认为 0.0) — 注意力概率的丢弃率。 - activation_dropout (
float
, optional, 默认为 0.0) — 全连接层内部激活函数的丢弃率。 - auxiliary_loss (
bool
, optional, 默认为False
) — 是否使用辅助解码损失(每个解码器层的损失)。 - position_embedding_type (
str
, optional, 默认为"sine"
) — 用于图像特征之上的位置嵌入类型。可选值为"sine"
或"learned"
。 - num_feature_levels (
int
, optional, 默认为 4) — 输入特征级别的数量。 - encoder_n_points (
int
, optional, 默认为 4) — 编码器中每个注意力头的每个特征级别中采样的键的数量。 - decoder_n_points (
int
, optional, 默认为 4) — 解码器中每个注意力头的每个特征级别中采样的键的数量。 - two_stage (
bool
, optional, 默认为True
) — 是否应用两阶段可变形 DETR,其中区域提议也由 Grounding DINO 的变体生成,然后送入解码器进行迭代边界框细化。 - class_cost (
float
, optional, 默认为 1.0) — 匈牙利匹配代价中分类错误的相对权重。 - bbox_cost (
float
, optional, 默认为 5.0) — 匈牙利匹配代价中边界框坐标的 L1 误差的相对权重。 - giou_cost (
float
, optional, 默认为 2.0) — 匈牙利匹配代价中边界框的广义 IoU 损失的相对权重。 - bbox_loss_coefficient (
float
, optional, 默认为 5.0) — 对象检测损失中 L1 边界框损失的相对权重。 - giou_loss_coefficient (
float
, optional, 默认为 2.0) — 对象检测损失中广义 IoU 损失的相对权重。 - focal_alpha (
float
, optional, 默认为 0.25) — focal loss 中的 Alpha 参数。 - disable_custom_kernels (
bool
, optional, 默认为False
) — 禁用自定义 CUDA 和 CPU 内核。此选项对于 ONNX 导出是必需的,因为 PyTorch ONNX 导出不支持自定义内核。 - max_text_len (
int
, optional, 默认为 256) — 文本输入的最大长度。 - text_enhancer_dropout (
float
, optional, 默认为 0.0) — 文本增强器的丢弃率。 - fusion_droppath (
float
, optional, 默认为 0.1) — 融合模块的 droppath 率。 - fusion_dropout (
float
, optional, 默认为 0.0) — 融合模块的丢弃率。 - embedding_init_target (
bool
, optional, 默认为True
) — 是否使用 Embedding 权重初始化目标。 - query_dim (
int
, optional, 默认为 4) — 查询向量的维度。 - decoder_bbox_embed_share (
bool
, optional, 默认为True
) — 是否为所有解码器层共享 bbox 回归头。 - two_stage_bbox_embed_share (
bool
, optional, 默认为False
) — 是否在两阶段 bbox 生成器和区域提议生成之间共享 bbox 嵌入。 - positional_embedding_temperature (
float
, optional, 默认为 20) — 与视觉主干网络一起使用的正弦位置嵌入的温度。 - init_std (
float
, optional, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, optional, 默认为 1e-05) — 层归一化层使用的 epsilon 值。
这是用于存储 GroundingDinoModel 配置的配置类。它用于根据指定的参数实例化一个 Grounding DINO 模型,定义模型架构。使用默认值实例化配置将产生与 Grounding DINO IDEA-Research/grounding-dino-tiny 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
示例
>>> 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
class transformers.GroundingDinoModel
< 源代码 >( config: GroundingDinoConfig )
参数
- config (GroundingDinoConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。
基础 Grounding DINO 模型(由主干网络和编码器-解码器 Transformer 组成),输出原始的隐藏状态,顶部没有任何特定的头。
该模型继承自 PreTrainedModel。请查阅超类文档,了解该库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
该模型也是 PyTorch torch.nn.Module 的子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与通用用法和行为相关的事项。
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 )
参数
- pixel_values (
torch.Tensor
,形状为(batch_size, num_channels, image_size, image_size)
) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参见{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
处理图像)。 - input_ids (
torch.LongTensor
,形状为(batch_size, text_sequence_length)
) — 词汇表中输入序列标记的索引。如果您提供填充,默认情况下将被忽略。索引可以使用 AutoTokenizer 获取。有关详细信息,请参见 BertTokenizer.call()。
- token_type_ids (
torch.LongTensor
,形状为(batch_size, text_sequence_length)
, optional) — 段标记索引,用于指示输入的第一部分和第二部分。索引在[0, 1]
中选择:0 对应于句子 A
标记,1 对应于句子 B
标记。 - attention_mask (
torch.Tensor
,形状为(batch_size, sequence_length)
, optional) — 掩码,用于避免对填充标记索引执行注意力。掩码值在[0, 1]
中选择:- 1 表示标记 未被掩码,
- 0 表示标记 被掩码。
- pixel_mask (
torch.Tensor
,形状为(batch_size, height, width)
, optional) — 掩码,用于避免对填充像素值执行注意力。掩码值在[0, 1]
中选择:- 1 表示像素是真实的(即 未被掩码),
- 0 表示像素是填充的(即 被掩码)。
- encoder_outputs (`
) -- 元组,由 (
last_hidden_state, *optional*:
hidden_states, *optional*:
attentions) 组成。
last_hidden_state形状为
(batch_size, sequence_length, hidden_size)`,optional) 是编码器最后一层输出的隐藏状态序列。用于解码器的交叉注意力。 - output_attentions (`
) -- 是否返回所有注意力层的注意力张量。有关更多详细信息,请参见返回张量下的
attentions`。 - output_hidden_states (`
) -- 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的
hidden_states`。 - return_dict (“) — 是否返回 ModelOutput 而不是普通元组。
GroundingDinoModel 的 forward 方法,重写了 `__call__` 特殊方法。
虽然前向传播的流程需要在此函数内定义,但之后应该调用 `Module` 实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoProcessor, AutoModel
>>> from PIL import Image
>>> import requests
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> 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
class transformers.GroundingDinoForObjectDetection
< 源代码 >( config: GroundingDinoConfig )
参数
- config (GroundingDinoConfig) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。
Grounding DINO 模型(由主干网络和编码器-解码器 Transformer 组成),顶部带有对象检测头,用于诸如 COCO 检测等任务。
该模型继承自 PreTrainedModel。请查阅超类文档,了解该库为其所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头等)。
该模型也是 PyTorch torch.nn.Module 的子类。可以像常规的 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与通用用法和行为相关的事项。
forward
< 源代码 >( pixel_values: FloatTensor 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: typing.Union[transformers.models.grounding_dino.modeling_grounding_dino.GroundingDinoEncoderOutput, tuple, NoneType] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None labels: typing.Optional[list[dict[str, typing.Union[torch.LongTensor, torch.FloatTensor]]]] = None )
参数
- pixel_values (
torch.FloatTensor
,形状为(batch_size, num_channels, image_size, image_size)
) — 对应于输入图像的张量。像素值可以使用{image_processor_class}
获取。有关详细信息,请参阅{image_processor_class}.__call__
({processor_class}
使用{image_processor_class}
来处理图像)。 - input_ids (
torch.LongTensor
,形状为(batch_size, text_sequence_length)
) — 词汇表中输入序列词元的索引。如果您提供填充,默认情况下将被忽略。索引可以使用 AutoTokenizer 获取。有关详细信息,请参阅 BertTokenizer.call()。
- token_type_ids (
torch.LongTensor
,形状为(batch_size, text_sequence_length)
,可选) — 分段词元索引,用于指示输入的第一部分和第二部分。索引在[0, 1]
中选择:0 对应于句子 A
词元,1 对应于句子 B
词元 - attention_mask (
torch.LongTensor
,形状为(batch_size, sequence_length)
,可选) — 用于避免在填充词元索引上执行注意力计算的掩码。掩码值在[0, 1]
中选择:- 对于未被掩码的词元,值为 1,
- 对于被掩码的词元,值为 0。
- pixel_mask (
torch.BoolTensor
,形状为(batch_size, height, width)
,可选) — 用于避免在填充像素值上执行注意力计算的掩码。掩码值在[0, 1]
中选择:- 对于真实像素(即未被掩码),值为 1,
- 对于填充像素(即被掩码),值为 0。
- encoder_outputs (
Union[~models.grounding_dino.modeling_grounding_dino.GroundingDinoEncoderOutput, tuple, NoneType]
) — 元组,包含 (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 而不是一个普通的元组。 - labels (
list[Dict]
,长度为(batch_size,)
,可选) — 用于计算二分匹配损失的标签。一个字典列表,每个字典至少包含以下2个键:‘class_labels’ 和 ‘boxes’(分别表示批处理中图像的类别标签和边界框)。类别标签本身应该是一个长度为(图像中边界框的数量,)
的torch.LongTensor
,而边界框是一个形状为(图像中边界框的数量, 4)
的torch.FloatTensor
。
GroundingDinoForObjectDetection 的 forward 方法重写了 __call__
特殊方法。
虽然前向传播的流程需要在此函数内定义,但之后应该调用 `Module` 实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> import requests
>>> 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)
>>> 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(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]