# RT-DETR

## 概述

RT-DETR 模型由 Wenyu Lv、Yian Zhao、Shangliang Xu、Jinman Wei、Guanzhong Wang、Cheng Cui、Yuning Du、Qingqing Dang 和 Yi Liu 在 [DETRs Beat YOLOs on Real-time Object Detection](https://huggingface.co/papers/2304.08069) 中提出。

RT-DETR 是一种目标检测模型，全称为“Real-Time DEtection Transformer”（实时检测 Transformer）。该模型专为执行目标检测任务而设计，旨在保持高精度的同时实现实时性能。借助在深度学习各领域广受欢迎的 Transformer 架构，RT-DETR 处理图像以识别并定位其中的多个对象。

该论文的摘要如下：

*近期，基于 Transformer 的端到端检测器（DETR）取得了卓越的性能。然而，DETR 计算成本高的问题尚未得到有效解决，这限制了其实际应用，也阻碍了其充分发挥无需后处理（如非极大值抑制，NMS）所带来的优势。在本文中，我们首先分析了 NMS 对现代实时目标检测器推理速度的影响，并建立了一个端到端的速度基准。为了避免 NMS 带来的推理延迟，我们提出了实时检测 Transformer（RT-DETR），据我们所知，这是首个实时端到端目标检测器。具体而言，我们设计了一种高效的混合编码器，通过解耦尺度内交互和跨尺度融合来高效处理多尺度特征，并提出了 IoU 感知的查询选择以改进目标查询的初始化。此外，我们提出的检测器支持通过选择不同的解码器层来灵活调整推理速度，且无需重新训练，这促进了实时目标检测器的实际应用。我们的 RT-DETR-L 在 COCO val2017 上达到了 53.0% AP，在 T4 GPU 上达到 114 FPS；而 RT-DETR-X 达到了 54.8% AP 和 74 FPS，在速度和精度上均超越了同等规模的所有 YOLO 检测器。此外，我们的 RT-DETR-R50 达到了 53.1% AP 和 108 FPS，在精度上比 DINO-Deformable-DETR-R50 高出 2.2% AP，在 FPS 上快约 21 倍。*

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

 RT-DETR 相对于 YOLO 模型的性能。摘自原始论文。

该模型版本由 [rafaelpadilla](https://huggingface.co/rafaelpadilla) 和 [sangbumchoi](https://github.com/SangbumChoi) 贡献。原始代码可在[此处](https://github.com/lyuwenyu/RT-DETR/)找到。

## 使用技巧

最初，图像会使用预训练的卷积神经网络进行处理，具体为原始代码中引用的 Resnet-D 变体。该网络从架构的最后三层中提取特征。随后，使用混合编码器将多尺度特征转换为图像特征的序列数组。然后，配备辅助预测头的解码器用于优化目标查询。此过程能够直接生成边界框，无需任何额外的后处理即可获取边界框的 logits 和坐标。该模型旨在与对应的 ImageProcessor 配合使用，将图像调整为 640x640 的尺寸。调整为其他尺寸通常会导致性能下降。

```python
import requests
import torch
from PIL import Image

from transformers import RTDetrForObjectDetection, RTDetrImageProcessor

url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)

image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd", device_map="auto")

inputs = image_processor(images=image, return_tensors="pt").to(model.device)

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

results = image_processor.post_process_object_detection(outputs, target_sizes=torch.tensor([(image.height, image.width)]), threshold=0.3)

for result in results:
    for score, label_id, box in zip(result["scores"], result["labels"], result["boxes"]):
        score, label = score.item(), label_id.item()
        box = [round(i, 2) for i in box.tolist()]
        print(f"{model.config.id2label[label]}: {score:.2f} {box}")
sofa: 0.97 [0.14, 0.38, 640.13, 476.21]
cat: 0.96 [343.38, 24.28, 640.14, 371.5]
cat: 0.96 [13.23, 54.18, 318.98, 472.22]
remote: 0.95 [40.11, 73.44, 175.96, 118.48]
remote: 0.92 [333.73, 76.58, 369.97, 186.99]
```

## 资源

以下是来自 Hugging Face 官方和社区（以 🌎 标识）的资源列表，可帮助您快速上手 RT-DETR。

- 另请参阅：[目标检测任务指南](../tasks/object_detection)。
- 有关在自定义数据集上进行 RT-DETR 推理和微调的 Notebook 可在[此处](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/RT-DETR)找到。🌎

## RTDetrConfig[[transformers.RTDetrConfig]]

#### transformers.RTDetrConfig[[transformers.RTDetrConfig]]

```python
transformers.RTDetrConfig(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, initializer_range: float = 0.01, initializer_bias_prior_prob: float | None = None, layer_norm_eps: float = 1e-05, batch_norm_eps: float = 1e-05, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, freeze_backbone_batch_norms: bool = True, encoder_hidden_dim: int = 256, encoder_in_channels: list[int] | tuple[int, ...] = (512, 1024, 2048), feat_strides: list[int] | tuple[int, ...] = (8, 16, 32), encoder_layers: int = 1, encoder_ffn_dim: int = 1024, encoder_attention_heads: int = 8, dropout: float | int = 0.0, activation_dropout: float | int = 0.0, encode_proj_layers: list[int] | tuple[int, ...] = (2,), positional_encoding_temperature: int = 10000, encoder_activation_function: str = 'gelu', activation_function: str = 'silu', eval_size: int | None = None, normalize_before: bool = False, hidden_expansion: float = 1.0, d_model: int = 256, num_queries: int = 300, decoder_in_channels: list[int] | tuple[int, ...] = (256, 256, 256), decoder_ffn_dim: int = 1024, num_feature_levels: int = 3, decoder_n_points: int = 4, decoder_layers: int = 6, decoder_attention_heads: int = 8, decoder_activation_function: str = 'relu', attention_dropout: float | int = 0.0, num_denoising: int = 100, label_noise_ratio: float = 0.5, box_noise_scale: float = 1.0, learn_initial_query: bool = False, anchor_image_size: int | list[int] | None = None, disable_custom_kernels: bool = True, with_box_refine: bool = True, matcher_alpha: float = 0.25, matcher_gamma: float = 2.0, matcher_class_cost: float = 2.0, matcher_bbox_cost: float = 5.0, matcher_giou_cost: float = 2.0, use_focal_loss: bool = True, auxiliary_loss: bool = True, focal_loss_alpha: float = 0.75, focal_loss_gamma: float = 2.0, weight_loss_vfl: float = 1.0, weight_loss_bbox: float = 5.0, weight_loss_giou: float = 2.0, eos_coefficient: float = 0.0001)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/configuration_rt_detr.py#L25)

**参数：**

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

initializer_range (`float`, *可选*，默认为 `0.01`) : 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

initializer_bias_prior_prob (`float`, *可选*) : 偏置初始化器用于初始化 `enc_score_head` 和 `class_embed` 偏置的先验概率。如果为 `None`，则在初始化模型权重时，`prior_prob` 的计算方式为 `prior_prob = 1 / (num_labels + 1)`。

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

batch_norm_eps (`float`, *可选*, 默认为 `1e-05`) : 批归一化层使用的 epsilon。

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

freeze_backbone_batch_norms (`bool`，*可选*，默认为 `True`)：是否冻结主干网络中的批归一化层。

encoder_hidden_dim (`int`，*可选*，默认为 `256`)：隐藏表示的维度。

encoder_in_channels (`list`，*可选*，默认为 `[512, 1024, 2048]`)：编码器的多层级特征输入。

feat_strides (`list[int]`，*可选*，默认为 `[8, 16, 32]`)：用于每个特征图的步长。

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

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

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

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

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

encode_proj_layers (`list[int]`，*可选*，默认为 `[2]`)：编码器中要使用的投影层索引。

positional_encoding_temperature (`int`，*可选*，默认为 10000)：用于创建位置编码的温度参数。

encoder_activation_function (`str`，*可选*，默认为 `"gelu"`)：编码器和池化器中使用的非线性激活函数（函数或字符串）。如果为字符串，则支持 `"gelu"`、`"relu"`、`"silu"` 和 `"gelu_new"`。

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

eval_size (`tuple[int, int]`，*可选*)：在考虑步长后，用于计算位置嵌入的有效高度和宽度。

normalize_before (`bool`, *可选*, 默认为 `False`) : 确定是否在 Transformer 编码器层的自注意力和前馈模块之前应用层归一化。

hidden_expansion (`float`, *可选*，默认为 1.0)：用于扩展 RepVGGBlock 和 CSPRepLayer 维度大小的扩展比率。

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

num_queries (`int`，*可选*，默认为 300)：对象查询的数量。

decoder_in_channels (`list`，*可选*，默认为 `[256, 256, 256]`)：解码器的多层特征维度

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

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

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

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

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

decoder_activation_function (`str`，*可选*，默认为 `"relu"`)：解码器中的非线性激活函数（函数或字符串）。如果为字符串，则支持 `"gelu"`、`"relu"`、`"silu"` 和 `"gelu_new"`。

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

num_denoising (`int`，*可选*，默认为 100)：用于对比去噪的去噪任务或查询的总数。

label_noise_ratio (`float`, *可选*，默认为 0.5)：应添加随机噪声的去噪标签比例。

box_noise_scale (`float`, *可选*, 默认值为 1.0) : 要添加到边界框的噪声的缩放或幅度。

learn_initial_query (`bool`，*可选*，默认为 `False`)：指示解码器的初始查询嵌入是否应在训练过程中学习

anchor_image_size (`tuple[int, int]`，*可选*)：在评估期间用于生成边界框锚点的输入图像的高度和宽度。如果为 None，则应用自动生成的锚点。

disable_custom_kernels (`bool`，*可选*，默认为 `True`)：是否禁用自定义内核。

with_box_refine (`bool`，*可选*，默认为 `True`)：是否应用迭代边界框细化，即每个解码器层基于上一层的预测结果来细化边界框。

matcher_alpha (`float`, *可选*，默认为 0.25)：匈牙利匹配器使用的参数 alpha。

matcher_gamma (`float`, *可选*, 默认值为 2.0) : 匈牙利匹配器使用的参数 gamma。

matcher_class_cost (`float`, *可选*，默认为 2.0)：匈牙利匹配器（Hungarian Matcher）中类别损失的相对权重。

matcher_bbox_cost (`float`, *可选*，默认为 5.0)：匈牙利匹配器（Hungarian Matcher）使用的边界框损失的相对权重。

matcher_giou_cost (`float`, *可选*，默认为 2.0)：匈牙利匹配器（Hungarian Matcher）所使用的 giou 损失的相对权重。

use_focal_loss (`bool`, *可选*, 默认为 `True`) : 指示是否应使用焦点损失的参数。

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

focal_loss_alpha (`float`, *可选*, 默认值为 0.75) : 用于计算焦点损失的参数 alpha。

focal_loss_gamma (`float`, *可选*, 默认值为 2.0) : 用于计算焦点损失的参数 gamma。

weight_loss_vfl (`float`, *可选*, 默认值为 1.0) : 变焦损失在目标检测损失中的相对权重。

weight_loss_bbox (`float`, *可选*, 默认值为 5.0) : 目标检测损失中 L1 边界框损失的相对权重。

weight_loss_giou (`float`, *可选*, 默认值为 2.0) : 在目标检测损失中，广义 IoU 损失的相对权重。

eos_coefficient (`float`, *可选*, 默认为 `0.0001`) : 目标检测损失中“无目标”类别的相对分类权重。

这是用于存储 RTDetrModel 配置的类。它根据指定的参数实例化 Rt Detr 模型，并定义模型架构。使用默认值实例化配置将生成与 [PekingU/rtdetr_r50vd](https://huggingface.co/PekingU/rtdetr_r50vd) 类似的配置。

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

示例：

```python
>>> from transformers import RTDetrConfig, RTDetrModel

>>> # Initializing a RT-DETR configuration
>>> configuration = RTDetrConfig()

>>> # Initializing a model (with random weights) from the configuration
>>> model = RTDetrModel(configuration)

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

## RTDetrResNetConfig[[transformers.RTDetrResNetConfig]]

#### transformers.RTDetrResNetConfig[[transformers.RTDetrResNetConfig]]

```python
transformers.RTDetrResNetConfig(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, is_encoder_decoder: bool = False, 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, num_channels: int = 3, embedding_size: int = 64, hidden_sizes: list[int] | tuple[int, ...] = (256, 512, 1024, 2048), depths: list[int] | tuple[int, ...] = (3, 4, 6, 3), layer_type: str = 'bottleneck', hidden_act: str = 'relu', downsample_in_first_stage: bool = False, downsample_in_bottleneck: bool = False, _out_features: list[str] | None = None, _out_indices: list[int] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/configuration_rt_detr_resnet.py#L25)

**参数：**

num_channels (`int`，*可选*，默认为 `3`)：输入通道数。

embedding_size (`int`，*可选*，默认为 `64`)：嵌入和隐藏状态的维度。

hidden_sizes (`Union[list[int], tuple[int, ...]]`，*可选*，默认为 `(256, 512, 1024, 2048)`)：模型每个阶段的维度（隐藏层大小）。

depths (`list[int]`，*可选*，默认为 `[3, 4, 6, 3]`)：每个阶段的深度（层数）。

layer_type (`str`，*可选*，默认为 `"bottleneck"`)：要使用的层，可以是 `"basic"`（用于较小的模型，如 resnet-18 或 resnet-34）或 `"bottleneck"`（用于较大的模型，如 resnet-50 及以上）。

hidden_act (`str`，*可选*，默认为 `"relu"`)：每个块中的非线性激活函数。如果为字符串，则支持 `"gelu"`、`"relu"`、`"selu"` 和 `"gelu_new"`。

downsample_in_first_stage (`bool`，*可选*，默认为 `False`)：如果为 `True`，第一阶段将使用 `stride` 为 2 的方式对输入进行下采样。

downsample_in_bottleneck (`bool`，*可选*，默认为 `False`)：如果为 `True`，ResNetBottleNeckLayer 中的第一个 1x1 卷积层将使用 `stride` 为 2 的方式对输入进行下采样。

这是用于存储 Rt Detr ResnetModel 配置的类。它根据指定的参数实例化 Rt Detr Resnet 模型，并定义模型架构。使用默认值实例化配置将得到与 [microsoft/resnet-50](https://huggingface.co/microsoft/resnet-50) 类似的配置。

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

示例：
```python
>>> from transformers import RTDetrResNetConfig, RTDetrResnetBackbone

>>> # Initializing a ResNet resnet-50 style configuration
>>> configuration = RTDetrResNetConfig()

>>> # Initializing a model (with random weights) from the resnet-50 style configuration
>>> model = RTDetrResnetBackbone(configuration)

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

## RTDetrImageProcessor[[transformers.RTDetrImageProcessor]]

#### transformers.RTDetrImageProcessor[[transformers.RTDetrImageProcessor]]

```python
transformers.RTDetrImageProcessor(**kwargs: *<class 'transformers.models.rt_detr.image_processing_rt_detr.RTDetrImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/image_processing_rt_detr.py#L131)

**参数：**

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

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

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

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*, *可选*, 默认为 `False`) : 是否对图像进行归一化。

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*, *可选*，默认为 `False`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

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`)：控制是否将注释转换为 RT_DETR 模型所期望的格式。将边界框转换为 `(center_x, center_y, width, height)` 格式，且范围在 `[0, 1]` 内。可通过 `preprocess` 方法中的 `do_convert_annotations` 参数进行覆盖。

构建一个 RTDetrImageProcessor 图像处理器。

#### preprocess[[transformers.RTDetrImageProcessor.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.rt_detr.image_processing_rt_detr.RTDetrImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/image_processing_rt_detr.py#L370)

**参数：**

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`)：控制是否将注释转换为 RT_DETR 模型所期望的格式。将边界框转换为 `(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.RTDetrImageProcessor.post_process_object_detection]]

```python
post_process_object_detection(outputs, threshold: float = 0.5, target_sizes: transformers.utils.generic.TensorType | list[tuple] = None, use_focal_loss: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/image_processing_rt_detr.py#L511)

**参数：**

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

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

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

use_focal_loss (`bool` 默认为 `True`)：指示是否使用 focal loss 来预测输出的变量。如果为 `True`，则应用 sigmoid 来计算每个检测的分数，否则使用 softmax 函数。

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

一个字典列表，每个字典包含模型对批次中某张图像预测的分数、标签和边界框。

将 [DetrForObjectDetection](/docs/transformers/main/zh/model_doc/detr#transformers.DetrForObjectDetection) 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的边界框。仅支持 PyTorch。

## RTDetrImageProcessorPil[[transformers.RTDetrImageProcessorPil]]

#### transformers.RTDetrImageProcessorPil[[transformers.RTDetrImageProcessorPil]]

```python
transformers.RTDetrImageProcessorPil(**kwargs: *<class 'transformers.models.rt_detr.image_processing_pil_rt_detr.RTDetrImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/image_processing_pil_rt_detr.py#L130)

**参数：**

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

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

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

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*, *可选*, 默认为 `False`) : 是否对图像进行归一化。

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*, *可选*，默认为 `False`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

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`)：控制是否将注释转换为 RT_DETR 模型所期望的格式。将边界框转换为 `(center_x, center_y, width, height)` 格式，且范围在 `[0, 1]` 内。可通过 `preprocess` 方法中的 `do_convert_annotations` 参数进行覆盖。

构建一个 RTDetrImageProcessor 图像处理器。

#### preprocess[[transformers.RTDetrImageProcessorPil.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.rt_detr.image_processing_pil_rt_detr.RTDetrImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/image_processing_pil_rt_detr.py#L379)

**参数：**

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`)：控制是否将注释转换为 RT_DETR 模型所期望的格式。将边界框转换为 `(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.RTDetrImageProcessorPil.post_process_object_detection]]

```python
post_process_object_detection(outputs, threshold: float = 0.5, target_sizes: transformers.utils.generic.TensorType | list[tuple] = None, use_focal_loss: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/image_processing_pil_rt_detr.py#L507)

**参数：**

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

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

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

use_focal_loss (`bool` 默认为 `True`)：指示是否使用 focal loss 来预测输出的变量。如果为 `True`，则应用 sigmoid 来计算每个检测的分数，否则使用 softmax 函数。

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

一个字典列表，每个字典包含模型对批次中某张图像预测的分数、标签和边界框。

将 [DetrForObjectDetection](/docs/transformers/main/zh/model_doc/detr#transformers.DetrForObjectDetection) 的原始输出转换为 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) 格式的边界框。仅支持 PyTorch。

## RTDetrModel[[transformers.RTDetrModel]]

#### transformers.RTDetrModel[[transformers.RTDetrModel]]

```python
transformers.RTDetrModel(config: RTDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/modeling_rt_detr.py#L1424)

**参数：**

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

RT-DETR 模型（由骨干网络和编码器-解码器组成），输出未经任何头部处理的原始隐藏状态。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.RTDetrModel.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: list[dict] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/modeling_rt_detr.py#L1544)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

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

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

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，除了传入展平的特征图（backbone + 投影层的输出）外，你还可以选择直接传入图像的展平表示。

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

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

`RTDetrModelOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[RTDetrModel](/docs/transformers/main/zh/model_doc/rt_detr#transformers.RTDetrModel) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **last_hidden_state**（形状为 `(batch_size, num_queries, hidden_size)` 的 `torch.Tensor`）-- 模型解码器最后一层输出的隐藏状态序列。
- **intermediate_hidden_states**（形状为 `(batch_size, config.decoder_layers, num_queries, hidden_size)` 的 `torch.Tensor`）-- 堆叠的中间隐藏状态（解码器每一层的输出）。
- **intermediate_logits**（形状为 `(batch_size, config.decoder_layers, sequence_length, config.num_labels)` 的 `torch.Tensor`）-- 堆叠的中间 logits（解码器每一层的 logits）。
- **intermediate_reference_points**（形状为 `(batch_size, config.decoder_layers, num_queries, 4)` 的 `torch.Tensor`）-- 堆叠的中间参考点（解码器每一层的参考点）。
- **intermediate_predicted_corners**（形状为 `(batch_size, config.decoder_layers, num_queries, 4)` 的 `torch.Tensor`）-- 堆叠的中间预测角点（解码器每一层预测的角点）。
- **initial_reference_points**（形状为 `(batch_size, 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[torch.Tensor]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器在注意力 softmax 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **cross_attentions** (`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**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型编码器最后一层输出的隐藏状态序列。
- **encoder_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[torch.Tensor]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回）-- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  编码器在注意力 softmax 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **init_reference_points**（形状为 `(batch_size, num_queries, 4)` 的 `torch.Tensor`）-- 通过 Transformer 解码器发送的初始参考点。
- **enc_topk_logits**（形状为 `(batch_size, sequence_length, config.num_labels)` 的 `torch.Tensor`）-- 预测的边界框分数，其中在编码器阶段会选取得分最高的 `config.two_stage_num_proposals` 个边界框作为区域提案。这是边界框二分类（即前景和背景）的输出。
- **enc_topk_bboxes**（形状为 `(batch_size, sequence_length, 4)` 的 `torch.Tensor`）-- 编码器阶段预测的边界框坐标的 Logits。
- **enc_outputs_class** (`torch.Tensor`，形状为 `(batch_size, sequence_length, config.num_labels)`，*可选*，当 `config.with_box_refine=True` 且 `config.two_stage=True` 时返回) -- 预测的边界框分数，其中得分最高的 `config.two_stage_num_proposals` 个边界框在第一阶段被选为区域建议。边界框二分类（即前景和背景）的输出。
- **enc_outputs_coord_logits** (`torch.Tensor`，形状为 `(batch_size, sequence_length, 4)`，*可选*，当 `config.with_box_refine=True` 且 `config.two_stage=True` 时返回) -- 第一阶段中预测的边界框坐标的 logits。
- **denoising_meta_values** (`dict`, *可选*) -- 用于去噪相关值的额外字典。

示例：

```python
>>> from transformers import AutoImageProcessor, RTDetrModel
>>> 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()))

>>> image_processor = AutoImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
>>> model = RTDetrModel.from_pretrained("PekingU/rtdetr_r50vd")

>>> inputs = image_processor(images=image, return_tensors="pt")

>>> outputs = model(**inputs)

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

## RTDetrForObjectDetection[[transformers.RTDetrForObjectDetection]]

#### transformers.RTDetrForObjectDetection[[transformers.RTDetrForObjectDetection]]

```python
transformers.RTDetrForObjectDetection(config: RTDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/modeling_rt_detr.py#L1750)

**参数：**

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

RT-DETR 模型（由骨干网络和编码器-解码器组成）输出边界框和 logits，以便进一步解码为分数和类别。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.RTDetrForObjectDetection.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, labels: list[dict] | None = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/modeling_rt_detr.py#L1771)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

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

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

inputs_embeds (`torch.Tensor`，形状为 `(batch_size, sequence_length, hidden_size)`，*可选*)：可选地，除了传入展平的特征图（backbone + 投影层的输出）外，你还可以选择直接传入图像的展平表示。

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

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

`RTDetrObjectDetectionOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（`None`）和输入。

[RTDetrForObjectDetection](/docs/transformers/main/zh/model_doc/rt_detr#transformers.RTDetrForObjectDetection) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，在提供 `labels` 时返回)) -- 总损失，是类别预测的负对数似然（交叉熵）与边界框损失的线性组合。后者定义为 L1 损失与广义尺度不变 IoU 损失的线性组合。
- **loss_dict** (`Dict`, *可选*) -- 包含各项单独损失的字典。适用于日志记录。
- **logits**（形状为 `(batch_size, num_queries, num_classes + 1)` 的 `torch.Tensor`）-- 所有查询的分类 logits（包括 no-object）。
- **pred_boxes**（形状为 `(batch_size, num_queries, 4)` 的 `torch.Tensor`）-- 所有查询的归一化框坐标，表示为 (center_x, center_y, width, height)。这些值在 [0, 1] 范围内归一化，相对于批次中每张图片的单独尺寸（忽略可能的填充）。您可以使用 [post_process_object_detection()](/docs/transformers/main/zh/model_doc/rt_detr#transformers.RTDetrImageProcessor.post_process_object_detection) 来获取未归一化（绝对）的边界框。
- **auxiliary_outputs** (`list[Dict]`, *可选*) -- 可选，仅在启用辅助损失（即 `config.auxiliary_loss` 设置为 `True`）且提供了标签时返回。它是一个字典列表，包含每个解码器层的上述两个键（`logits` 和 `pred_boxes`）。
- **last_hidden_state**（形状为 `(batch_size, num_queries, hidden_size)` 的 `torch.Tensor`）-- 模型解码器最后一层输出的隐藏状态序列。
- **intermediate_hidden_states**（形状为 `(batch_size, config.decoder_layers, num_queries, hidden_size)` 的 `torch.Tensor`）-- 堆叠的中间隐藏状态（解码器每一层的输出）。
- **intermediate_logits**（形状为 `(batch_size, config.decoder_layers, num_queries, config.num_labels)` 的 `torch.Tensor`）-- 堆叠的中间 logits（解码器每一层的 logits）。
- **intermediate_reference_points**（形状为 `(batch_size, config.decoder_layers, num_queries, 4)` 的 `torch.Tensor`）-- 堆叠的中间参考点（解码器每一层的参考点）。
- **intermediate_predicted_corners**（形状为 `(batch_size, config.decoder_layers, num_queries, 4)` 的 `torch.Tensor`）-- 堆叠的中间预测角点（解码器每一层预测的角点）。
- **initial_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[torch.Tensor]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  解码器在注意力 softmax 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **cross_attentions** (`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**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*）-- 模型编码器最后一层输出的隐藏状态序列。
- **encoder_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[torch.Tensor]`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回）-- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

  编码器在注意力 softmax 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **init_reference_points**（形状为 `(batch_size, num_queries, 4)` 的 `torch.Tensor`）-- 通过 Transformer 解码器发送的初始参考点。
- **enc_topk_logits**（形状为 `(batch_size, sequence_length, config.num_labels)` 的 `torch.Tensor`，*可选*，当 `config.with_box_refine=True` 且 `config.two_stage=True` 时返回）-- 编码器中预测的边界框坐标的 logits。
- **enc_topk_bboxes**（形状为 `(batch_size, sequence_length, 4)` 的 `torch.Tensor`，*可选*，当 `config.with_box_refine=True` 且 `config.two_stage=True` 时返回）-- 编码器中预测的边界框坐标的 Logits。
- **enc_outputs_class** (`torch.Tensor`，形状为 `(batch_size, sequence_length, config.num_labels)`，*可选*，当 `config.with_box_refine=True` 且 `config.two_stage=True` 时返回) -- 预测的边界框分数，其中得分最高的 `config.two_stage_num_proposals` 个边界框在第一阶段被选为区域建议。边界框二分类（即前景和背景）的输出。
- **enc_outputs_coord_logits** (`torch.Tensor`，形状为 `(batch_size, sequence_length, 4)`，*可选*，当 `config.with_box_refine=True` 且 `config.two_stage=True` 时返回) -- 第一阶段中预测的边界框坐标的 logits。
- **denoising_meta_values** (`dict`, *可选*) -- 用于去噪相关值的额外字典

示例：

```python
>>> from transformers import RTDetrImageProcessor, RTDetrForObjectDetection
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch

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

>>> image_processor = RTDetrImageProcessor.from_pretrained("PekingU/rtdetr_r50vd")
>>> model = RTDetrForObjectDetection.from_pretrained("PekingU/rtdetr_r50vd")

>>> # prepare image for the model
>>> inputs = image_processor(images=image, return_tensors="pt")

>>> # forward pass
>>> outputs = model(**inputs)

>>> logits = outputs.logits
>>> list(logits.shape)
[1, 300, 80]

>>> boxes = outputs.pred_boxes
>>> list(boxes.shape)
[1, 300, 4]

>>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
>>> target_sizes = torch.tensor([image.size[::-1]])
>>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
...     0
... ]

>>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
...     box = [round(i, 2) for i in box.tolist()]
...     print(
...         f"Detected {model.config.id2label[label.item()]} with confidence "
...         f"{round(score.item(), 3)} at location {box}"
...     )
Detected sofa with confidence 0.97 at location [0.14, 0.38, 640.13, 476.21]
Detected cat with confidence 0.96 at location [343.38, 24.28, 640.14, 371.5]
Detected cat with confidence 0.958 at location [13.23, 54.18, 318.98, 472.22]
Detected remote with confidence 0.951 at location [40.11, 73.44, 175.96, 118.48]
Detected remote with confidence 0.924 at location [333.73, 76.58, 369.97, 186.99]
```

## RTDetrResNetBackbone[[transformers.RTDetrResNetBackbone]]

#### transformers.RTDetrResNetBackbone[[transformers.RTDetrResNetBackbone]]

```python
transformers.RTDetrResNetBackbone(config: RTDetrResNetConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/modeling_rt_detr_resnet.py#L349)

**参数：**

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

ResNet 骨干网络，用于与 RTDETR 等框架配合使用。

该模型继承自 [PreTrainedModel](/docs/transformers/main/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.RTDetrResNetBackbone.forward]]

```python
forward(pixel_values: Tensor, output_hidden_states: bool | None = None, return_dict: bool | None = None, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/rt_detr/modeling_rt_detr_resnet.py#L362)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 `image_processor_class` 获取像素值。有关详细信息，请参阅 `image_processor_class.__call__`（`processor_class` 使用 `image_processor_class` 处理图像）。

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

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

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

`BackboneOutput` 或 `torch.Tensor` 元组（如果传入 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[RTDetrResNetConfig](/docs/transformers/main/zh/model_doc/rt_detr#transformers.RTDetrResNetConfig)）和输入。

[RTDetrResNetBackbone](/docs/transformers/main/zh/model_doc/rt_detr#transformers.RTDetrResNetBackbone) 的 forward 方法重写了 `__call__` 特殊方法。

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

- **feature_maps**（形状为 `(batch_size, num_channels, height, width)` 的 `tuple(torch.Tensor)`）-- 各阶段的特征图。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（包含嵌入层的输出以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)` 或 `(batch_size, num_channels, height, width)`，具体取决于骨干网络。

  模型在每个阶段输出处的隐藏状态，以及初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。仅当主干网络使用注意力机制时适用。

  经过注意力 softmax 后的注意力权重，用于在自注意力头中计算加权平均值。

  示例：

```python
>>> from transformers import RTDetrResNetConfig, RTDetrResNetBackbone
>>> import torch
precation import deprecate_kwarg
precation import deprecate_kwarg
precation import deprecate_kwarg
utils.deprecation import deprecate_kwarg
utils.deprecation import deprecate_kwarg

>>> config = RTDetrResNetConfig()
>>> model = RTDetrResNetBackbone(config)

>>> pixel_values = torch.randn(1, 3, 224, 224)

>>> with torch.no_grad():
...     outputs = model(pixel_values)

>>> feature_maps = outputs.feature_maps
>>> list(feature_maps[-1].shape)
[1, 2048, 7, 7]
```

