Transformers 文件

OmDet-Turbo

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

OmDet-Turbo

PyTorch

概述

OmDet-Turbo 模型由 Tiancheng Zhao, Peng Liu, Xuan He, Lu Zhang, Kyusong Lee 在 Real-time Transformer-based Open-Vocabulary Detection with Efficient Fusion Head 中提出。OmDet-Turbo 結合了 RT-DETR 的元件,並引入了一種快速多模態融合模組,以在保持高精度的同時實現即時開放詞彙目標檢測能力。該基礎模型在 COCO 零樣本上實現了高達 100.2 FPS 和 53.4 AP 的效能。

論文摘要如下:

端到端基於 Transformer 的檢測器 (DETR) 透過整合語言模態在閉集和開放詞彙目標檢測 (OVD) 任務中都表現出卓越的效能。然而,其高計算要求阻礙了它們在即時目標檢測 (OD) 場景中的實際應用。在本文中,我們審視了 OVDEval 基準中兩個領先模型 OmDet 和 Grounding-DINO 的侷限性,並引入了 OmDet-Turbo。這個新穎的基於 Transformer 的即時 OVD 模型具有創新的高效融合頭 (EFH) 模組,旨在緩解 OmDet 和 Grounding-DINO 中觀察到的瓶頸。值得注意的是,OmDet-Turbo-Base 在應用 TensorRT 和語言快取技術後,實現了 100.2 幀每秒 (FPS) 的速度。在 COCO 和 LVIS 資料集上的零樣本場景中,OmDet-Turbo 的效能幾乎與當前最先進的監督模型持平。此外,它還在 ODinW 和 OVDEval 上建立了新的最先進基準,AP 分別達到 30.1 和 NMS-AP 達到 26.86。OmDet-Turbo 在基準資料集上卓越的效能和卓越的推理速度突顯了其在工業應用中的實用性,使其成為即時目標檢測任務的有力選擇。

drawing OmDet-Turbo 架構概述。摘自原始論文

該模型由yonigozlan貢獻。原始程式碼可在此處找到。

使用技巧

與其他零樣本目標檢測模型(如Grounding DINO)相比,OmDet-Turbo 的一個獨特屬性是其解耦的類別和提示嵌入結構,允許快取文字嵌入。這意味著模型需要同時輸入類別和任務,其中類別是我們想要檢測的物件列表,任務是用於指導開放詞彙檢測的接地文字。這種方法限制了開放詞彙檢測的範圍,並加快了解碼過程。

OmDetTurboProcessor 用於準備類別、任務和影像三元組。任務輸入是可選的,如果未提供,將預設為 "檢測 [類別1], [類別2], [類別3], ..."。為了處理模型的輸出結果,可以使用 OmDetTurboProcessor 中的 post_process_grounded_object_detection 函式。值得注意的是,該函式接受輸入的類別,因為與其他零樣本目標檢測模型不同,類別和任務嵌入的解耦意味著在後處理步驟中無需對預測的類別嵌入進行解碼,預測的類別可以直接與輸入的類別匹配。

使用示例

單影像推理

以下是載入模型並準備輸入以在單個影像上執行零樣本目標檢測的方法

>>> import torch
>>> import requests
>>> from PIL import Image

>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection

>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> text_labels = ["cat", "remote"]
>>> inputs = processor(image, text=text_labels, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
...     outputs,
...     target_sizes=[(image.height, image.width)],
...     text_labels=text_labels,
...     threshold=0.3,
...     nms_threshold=0.3,
... )
>>> result = results[0]
>>> boxes, scores, text_labels = result["boxes"], result["scores"], result["text_labels"]
>>> for box, score, text_label in zip(boxes, scores, text_labels):
...     box = [round(i, 2) for i in box.tolist()]
...     print(f"Detected {text_label} with confidence {round(score.item(), 3)} at location {box}")
Detected remote with confidence 0.768 at location [39.89, 70.35, 176.74, 118.04]
Detected cat with confidence 0.72 at location [11.6, 54.19, 314.8, 473.95]
Detected remote with confidence 0.563 at location [333.38, 75.77, 370.7, 187.03]
Detected cat with confidence 0.552 at location [345.15, 23.95, 639.75, 371.67]

多影像推理

OmDet-Turbo 可以執行批處理多影像推理,支援在同一批次中使用不同的文字提示和類別

>>> import torch
>>> import requests
>>> from io import BytesIO
>>> from PIL import Image
>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection

>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")

>>> url1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image1 = Image.open(BytesIO(requests.get(url1).content)).convert("RGB")
>>> text_labels1 = ["cat", "remote"]
>>> task1 = "Detect {}.".format(", ".join(text_labels1))

>>> url2 = "http://images.cocodataset.org/train2017/000000257813.jpg"
>>> image2 = Image.open(BytesIO(requests.get(url2).content)).convert("RGB")
>>> text_labels2 = ["boat"]
>>> task2 = "Detect everything that looks like a boat."

>>> url3 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
>>> image3 = Image.open(BytesIO(requests.get(url3).content)).convert("RGB")
>>> text_labels3 = ["statue", "trees"]
>>> task3 = "Focus on the foreground, detect statue and trees."

>>> inputs = processor(
...     images=[image1, image2, image3],
...     text=[text_labels1, text_labels2, text_labels3],
...     task=[task1, task2, task3],
...     return_tensors="pt",
... )

>>> with torch.no_grad():
...     outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
...     outputs,
...     text_labels=[text_labels1, text_labels2, text_labels3],
...     target_sizes=[(image.height, image.width) for image in [image1, image2, image3]],
...     threshold=0.2,
...     nms_threshold=0.3,
... )

>>> for i, result in enumerate(results):
...     for score, text_label, box in zip(
...         result["scores"], result["text_labels"], result["boxes"]
...     ):
...         box = [round(i, 1) for i in box.tolist()]
...         print(
...             f"Detected {text_label} with confidence "
...             f"{round(score.item(), 2)} at location {box} in image {i}"
...         )
Detected remote with confidence 0.77 at location [39.9, 70.4, 176.7, 118.0] in image 0
Detected cat with confidence 0.72 at location [11.6, 54.2, 314.8, 474.0] in image 0
Detected remote with confidence 0.56 at location [333.4, 75.8, 370.7, 187.0] in image 0
Detected cat with confidence 0.55 at location [345.2, 24.0, 639.8, 371.7] in image 0
Detected boat with confidence 0.32 at location [146.9, 219.8, 209.6, 250.7] in image 1
Detected boat with confidence 0.3 at location [319.1, 223.2, 403.2, 238.4] in image 1
Detected boat with confidence 0.27 at location [37.7, 220.3, 84.0, 235.9] in image 1
Detected boat with confidence 0.22 at location [407.9, 207.0, 441.7, 220.2] in image 1
Detected statue with confidence 0.73 at location [544.7, 210.2, 651.9, 502.8] in image 2
Detected trees with confidence 0.25 at location [3.9, 584.3, 391.4, 785.6] in image 2
Detected trees with confidence 0.25 at location [1.4, 621.2, 118.2, 787.8] in image 2
Detected statue with confidence 0.2 at location [428.1, 205.5, 767.3, 759.5] in image 2

OmDetTurboConfig

class transformers.OmDetTurboConfig

< >

( text_config = None backbone_config = None use_timm_backbone = True backbone = 'swin_tiny_patch4_window7_224' backbone_kwargs = None use_pretrained_backbone = False apply_layernorm_after_vision_backbone = True image_size = 640 disable_custom_kernels = False layer_norm_eps = 1e-05 batch_norm_eps = 1e-05 init_std = 0.02 text_projection_in_dim = 512 text_projection_out_dim = 512 task_encoder_hidden_dim = 1024 class_embed_dim = 512 class_distance_type = 'cosine' num_queries = 900 csp_activation = 'silu' conv_norm_activation = 'gelu' encoder_feedforward_activation = 'relu' encoder_feedforward_dropout = 0.0 encoder_dropout = 0.0 hidden_expansion = 1 vision_features_channels = [256, 256, 256] encoder_hidden_dim = 256 encoder_in_channels = [192, 384, 768] encoder_projection_indices = [2] encoder_attention_heads = 8 encoder_dim_feedforward = 2048 encoder_layers = 1 positional_encoding_temperature = 10000 num_feature_levels = 3 decoder_hidden_dim = 256 decoder_num_heads = 8 decoder_num_layers = 6 decoder_activation = 'relu' decoder_dim_feedforward = 2048 decoder_num_points = 4 decoder_dropout = 0.0 eval_size = None learn_initial_query = False cache_size = 100 is_encoder_decoder = True **kwargs )

引數

  • text_config (PretrainedConfig, 可選) — 文字骨幹的配置。
  • backbone_config (PretrainedConfig, 可選) — 視覺骨幹的配置。
  • use_timm_backbone (bool, 可選, 預設為 True) — 是否使用 timm 作為視覺骨幹。
  • backbone (str, 可選, 預設為 "swin_tiny_patch4_window7_224") — 要使用的預訓練視覺骨幹的名稱。如果 use_pretrained_backbone=False,則使用具有相同架構 backbone 的隨機初始化骨幹。
  • backbone_kwargs (dict, 可選) — 視覺骨幹的額外關鍵字引數。
  • use_pretrained_backbone (bool, 可選, 預設為 False) — 是否使用預訓練的視覺骨幹。
  • apply_layernorm_after_vision_backbone (bool, 可選, 預設為 True) — 是否在視覺骨幹輸出的特徵圖上應用層歸一化。
  • image_size (int, 可選, 預設為 640) — 每張影像的大小(解析度)。
  • disable_custom_kernels (bool, 可選, 預設為 False) — 是否停用自定義核心。
  • layer_norm_eps (float, 可選, 預設為 1e-05) — 層歸一化的 epsilon 值。
  • batch_norm_eps (float, 可選, 預設為 1e-05) — 批歸一化的 epsilon 值。
  • init_std (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的 truncated_normal_initializer 的標準差。
  • text_projection_in_dim (int, 可選, 預設為 512) — 文字投影的輸入維度。
  • text_projection_out_dim (int, 可選, 預設為 512) — 文字投影的輸出維度。
  • task_encoder_hidden_dim (int, 可選, 預設為 1024) — 任務編碼器的前饋維度。
  • class_embed_dim (int, 可選, 預設為 512) — 類別嵌入的維度。
  • class_distance_type (str, 可選, 預設為 "cosine") — 用於將預測類別與投影類別嵌入進行比較的距離型別。可以是 "cosine""dot"
  • num_queries (int, 可選, 預設為 900) — 查詢的數量。
  • csp_activation (str, 可選, 預設為 "silu") — 編碼器交叉階段部分 (CSP) 網路的啟用函式。
  • conv_norm_activation (str, 可選, 預設為 "gelu") — 編碼器 ConvNormLayer 層的啟用函式。
  • encoder_feedforward_activation (str, 可選, 預設為 "relu") — 編碼器前饋網路的啟用函式。
  • encoder_feedforward_dropout (float, 可選, 預設為 0.0) — 編碼器前饋網路啟用後的 dropout 率。
  • encoder_dropout (float, 可選, 預設為 0.0) — 編碼器多頭注意力模組的 dropout 率。
  • hidden_expansion (int, 可選, 預設為 1) — 編碼器中 CSP 網路的隱藏擴充套件。
  • vision_features_channels (tuple(int), 可選, 預設為 [256, 256, 256]) — 用作解碼器輸入的投影視覺特徵通道。
  • encoder_hidden_dim (int, 可選, 預設為 256) — 編碼器的隱藏維度。
  • encoder_in_channels (List(int), 可選, 預設為 [192, 384, 768]) — 編碼器的輸入通道。
  • encoder_projection_indices (List(int), 可選, 預設為 [2]) — 每個層投影的輸入特徵的索引。
  • encoder_attention_heads (int, 可選, 預設為 8) — 編碼器的注意力頭數量。
  • encoder_dim_feedforward (int, 可選, 預設為 2048) — 編碼器的前饋維度。
  • encoder_layers (int, 可選, 預設為 1) — 編碼器中的層數。
  • positional_encoding_temperature (int, 可選, 預設為 10000) — 編碼器中的位置編碼溫度。
  • num_feature_levels (int, 可選, 預設為 3) — 解碼器多尺度可變形注意力模組的特徵層數。
  • decoder_hidden_dim (int, 可選, 預設為 256) — 解碼器的隱藏維度。
  • decoder_num_heads (int, 可選, 預設為 8) — 解碼器的頭數量。
  • decoder_num_layers (int, 可選, 預設為 6) — 解碼器的層數。
  • decoder_activation (str, 可選, 預設為 "relu") — 解碼器的啟用函式。
  • decoder_dim_feedforward (int, 可選, 預設為 2048) — 解碼器的前饋維度。
  • decoder_num_points (int, 可選, 預設為 4) — 在解碼器多尺度可變形注意力模組中取樣的點數。
  • decoder_dropout (float, 可選, 預設為 0.0) — 解碼器的 dropout 率。
  • eval_size (tuple[int, int], 可選) — 用於計算考慮步幅後位置嵌入的有效高度和寬度的尺寸(請參見 RTDetr)。
  • learn_initial_query (bool, 可選, 預設為 False) — 是否學習初始查詢。
  • cache_size (int, 可選, 預設為 100) — 類別和提示快取的快取大小。
  • is_encoder_decoder (bool, 可選, 預設為 True) — 模型是否用作編碼器-解碼器模型。
  • kwargs (dict[str, Any], 可選) — 架構中的其他引數。kwargs 中的值將作為配置的一部分儲存,可用於控制模型輸出。

這是一個配置類,用於儲存 OmDetTurboForObjectDetection 的配置。它用於根據指定的引數例項化 OmDet-Turbo 模型,定義模型架構。使用預設值例項化配置將產生類似於 OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf 架構的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請參閱 PretrainedConfig 的文件。

示例

>>> from transformers import OmDetTurboConfig, OmDetTurboForObjectDetection

>>> # Initializing a OmDet-Turbo omlab/omdet-turbo-swin-tiny-hf style configuration
>>> configuration = OmDetTurboConfig()

>>> # Initializing a model (with random weights) from the omlab/omdet-turbo-swin-tiny-hf style configuration
>>> model = OmDetTurboForObjectDetection(configuration)

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

OmDetTurboProcessor

class transformers.OmDetTurboProcessor

< >

( image_processor tokenizer )

引數

  • image_processor (DetrImageProcessor) — DetrImageProcessor 的例項。影像處理器是必需輸入。
  • tokenizer (AutoTokenizer) — [‘PreTrainedTokenizer`] 的例項。分詞器是必需輸入。

構建一個 OmDet-Turbo 處理器,它將可變形 DETR 影像處理器和 AutoTokenizer 封裝到一個處理器中。

OmDetTurboProcessor 提供 DetrImageProcessorAutoTokenizer 的所有功能。有關更多資訊,請參閱 __call__()decode() 的文件字串。

post_process_grounded_object_detection

< >

( outputs: OmDetTurboObjectDetectionOutput text_labels: typing.Union[list[str], list[list[str]], NoneType] = None threshold: float = 0.3 nms_threshold: float = 0.5 target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple], NoneType] = None max_num_det: typing.Optional[int] = None ) list[Dict]

引數

  • outputs (OmDetTurboObjectDetectionOutput) — 模型的原始輸出。
  • text_labels (Union[list[str], list[list[str]]], 可選) — 輸入的類別名稱。如果未提供,text_labels 將在 outputs 中設定為 None
  • threshold (float, 預設為 0.3) — 僅返回置信度得分超過此閾值的檢測結果。
  • nms_threshold (float, 預設為 0.5) — 用於邊界框非極大值抑制的閾值。值介於 [0, 1] 之間。
  • target_sizes (torch.Tensorlist[tuple[int, int]], 可選) — 形狀為 (batch_size, 2) 的張量或包含批次中每張影像目標大小 (height, width) 的元組列表(tuple[int, int])。如果未設定,預測將不會被調整大小。
  • max_num_det (int, 可選) — 返回的最大檢測數量。

返回

list[Dict]

一個字典列表,每個字典包含模型預測的批次中影像的分數、類別和邊界框。

OmDetTurboForObjectDetection 的原始輸出轉換為 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的最終邊界框,並獲取相關的文字類別。

OmDetTurboForObjectDetection

class transformers.OmDetTurboForObjectDetection

< >

( config: OmDetTurboConfig )

引數

  • config (OmDetTurboConfig) — 包含模型所有引數的模型配置類。使用配置檔案初始化並不會載入與模型相關的權重,只加載配置。請檢視 from_pretrained() 方法來載入模型權重。

OmDetTurbo 模型(由視覺和文字骨幹,以及編碼器-解碼器架構組成)輸出用於 COCO 檢測等任務的邊界框和類別分數。

該模型繼承自 PreTrainedModel。請檢視超類文件,瞭解庫為所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

該模型也是 PyTorch torch.nn.Module 的子類。將其作為常規 PyTorch 模組使用,並參考 PyTorch 文件以瞭解所有與一般使用和行為相關的事項。

前向

< >

( pixel_values: FloatTensor classes_input_ids: LongTensor classes_attention_mask: LongTensor tasks_input_ids: LongTensor tasks_attention_mask: LongTensor classes_structure: LongTensor labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutputtuple(torch.FloatTensor)

引數

  • pixel_values (torch.FloatTensor,形狀為 (batch_size, num_channels, image_size, image_size)) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參見 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • classes_input_ids (torch.LongTensor,形狀為 (total_classes (>= batch_size), sequence_length)) — 語言模型詞彙表中輸入類別序列 token 的索引。每個任務可以提供多個類別,因此 tokenized 類別是扁平的,類別結構在 classes_structure 引數中提供。

    索引可以使用 OmDetTurboProcessor 獲取。有關詳細資訊,請參見 OmDetTurboProcessor.__call__()

    什麼是輸入 ID?

  • classes_attention_mask (torch.BoolTensor,形狀為 (total_classes (>= batch_size), num_classes, sequence_length)) — 類別的注意力掩碼。這是一個二進位制掩碼,指示應關注哪些 token,不應關注哪些 token。
  • tasks_input_ids (torch.LongTensor,形狀為 (batch_size, sequence_length)) — 語言模型詞彙表中輸入任務序列 token 的索引。

    索引可以使用 OmDetTurboProcessor 獲取。有關詳細資訊,請參見 OmDetTurboProcessor.__call__()

    什麼是輸入 ID?

  • tasks_attention_mask (torch.BoolTensor,形狀為 (batch_size, sequence_length)) — 任務的注意力掩碼。這是一個二進位制掩碼,指示應關注哪些 token,不應關注哪些 token。
  • classes_structure (torch.LongTensor,形狀為 (batch_size)) — 類別的結構。此張量指示每個任務的類別數量。
  • labels (torch.LongTensor,形狀為 (batch_size, sequence_length), 可選) — 用於計算掩碼語言建模損失的標籤。索引應為 [0, ..., config.vocab_size] 或 -100(請參見 input_ids 文件字串)。索引設定為 -100 的 token 將被忽略(掩碼),損失僅針對標籤在 [0, ..., config.vocab_size] 中的 token 計算。
  • output_attentions (bool, 可選) — 是否返回所有注意力層的注意力張量。有關更多詳細資訊,請參見返回張量下的 attentions
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參見返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是否返回 ModelOutput 而不是純元組。

返回

transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutputtuple(torch.FloatTensor)

一個 transformers.models.omdet_turbo.modeling_omdet_turbo.OmDetTurboObjectDetectionOutputtorch.FloatTensor 元組(如果傳遞 return_dict=False 或當 config.return_dict=False 時),包含取決於配置 (OmDetTurboConfig) 和輸入的各種元素。

  • loss (torch.FloatTensor, 可選, 預設為 None) — 損失值。
  • decoder_coord_logits (torch.FloatTensor,形狀為 (batch_size, num_queries, 4)) — 物件的預測座標對數。
  • decoder_class_logits (torch.FloatTensor,形狀為 (batch_size, num_queries, num_classes)) — 物件的預測類別。
  • init_reference_points (torch.FloatTensor,形狀為 (batch_size, num_queries, 4)) — 初始參考點。
  • intermediate_reference_points (tuple[tuple[torch.FloatTensor]], 可選, 預設為 None) — 中間參考點。
  • encoder_coord_logits (torch.FloatTensor,形狀為 (batch_size, num_queries, 4)) — 編碼器預測的物件的座標。
  • encoder_class_logits (tuple[torch.FloatTensor].encoder_class_logits, 預設為 None) — 編碼器預測的物件的類別。
  • encoder_extracted_states (torch.FloatTensor, 可選, 預設為 None) — 從編碼器的特徵金字塔網路 (FPN) 和路徑聚合網路 (PAN) 中提取的狀態。
  • decoder_hidden_states (tuple[torch.FloatTensor], 可選) — torch.FloatTensor 元組(一個用於嵌入輸出 + 一個用於每層輸出),形狀為 (batch_size, sequence_length, hidden_size)。模型在每層輸出處的隱藏狀態以及初始嵌入輸出。
  • decoder_attentions (tuple[tuple[torch.FloatTensor]], 可選) — torch.FloatTensor 元組(每層一個注意力),形狀為 (batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 後的注意力權重,用於計算自注意力、交叉注意力和多尺度可變形注意力頭中的加權平均值。
  • encoder_hidden_states (tuple[torch.FloatTensor], 可選) — torch.FloatTensor 元組(一個用於嵌入輸出 + 一個用於每層輸出),形狀為 (batch_size, sequence_length, hidden_size)。模型在每層輸出處的隱藏狀態以及初始嵌入輸出。
  • encoder_attentions (tuple[tuple[torch.FloatTensor]], 可選) — torch.FloatTensor 元組(每層一個注意力),形狀為 (batch_size, num_heads, sequence_length, sequence_length)。注意力 softmax 後的注意力權重,用於計算自注意力、交叉注意力和多尺度可變形注意力頭中的加權平均值。
  • classes_structure (torch.LongTensor, 可選) — 每張影像查詢的類別數量。

OmDetTurboForObjectDetection 前向方法,覆蓋 __call__ 特殊方法。

儘管前向傳播的配方需要在此函式中定義,但在此之後應呼叫 Module 例項,而不是此函式,因為前者負責執行預處理和後處理步驟,而後者則默默地忽略它們。

示例

>>> import requests
>>> from PIL import Image

>>> from transformers import AutoProcessor, OmDetTurboForObjectDetection

>>> processor = AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
>>> model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> classes = ["cat", "remote"]
>>> task = "Detect {}.".format(", ".join(classes))
>>> inputs = processor(image, text=classes, task=task, return_tensors="pt")

>>> outputs = model(**inputs)

>>> # convert outputs (bounding boxes and class logits)
>>> results = processor.post_process_grounded_object_detection(
...     outputs,
...     classes=classes,
...     target_sizes=[image.size[::-1]],
...     score_threshold=0.3,
...     nms_threshold=0.3,
>>> )[0]
>>> for score, class_name, box in zip(results["scores"], results["classes"], results["boxes"]):
...     box = [round(i, 1) for i in box.tolist()]
...     print(
...         f"Detected {class_name} with confidence "
...         f"{round(score.item(), 2)} at location {box}"
...     )
Detected remote with confidence 0.76 at location [39.9, 71.3, 176.5, 117.9]
Detected cat with confidence 0.72 at location [345.1, 22.5, 639.7, 371.9]
Detected cat with confidence 0.65 at location [12.7, 53.8, 315.5, 475.3]
Detected remote with confidence 0.57 at location [333.4, 75.6, 370.7, 187.0]
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.