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]