# 条件 DETR

## 概述

Conditional DETR 模型由 Depu Meng、Xiaokang Chen、Zejia Fan、Gang Zeng、Houqiang Li、Yuhui Yuan、Lei Sun 和 Jingdong Wang 在 [Conditional DETR for Fast Training Convergence](https://huggingface.co/papers/2108.06152) 中提出。Conditional DETR 提出了一种条件交叉注意力机制，以实现 DETR 的快速训练。与 DETR 相比，Conditional DETR 的收敛速度提升了 6.7 倍至 10 倍。

该论文的摘要如下：

*近期开发的 DETR 方法将 Transformer 编码器和解码器架构应用于目标检测，并取得了令人瞩目的性能。本文解决了训练收敛缓慢这一关键问题，并提出了一种用于加速 DETR 训练的有条件交叉注意力机制。我们的方法基于以下动机：DETR 中的交叉注意力高度依赖于内容嵌入来定位四个极值点并预测边界框，这增加了对高质量内容嵌入的需求，从而提高了训练难度。我们提出的方法称为有条件 DETR，它从解码器嵌入中学习一个有条件空间查询，用于解码器的多头交叉注意力。其优势在于，通过有条件空间查询，每个交叉注意力头能够关注包含不同区域的带状区域，例如一个物体极值点或物体框内的某个区域。这缩小了用于目标分类和边界框回归的不同区域的空间定位范围，从而降低了对内容嵌入的依赖并简化了训练。实验结果表明，对于骨干网络 R50 和 R101，有条件 DETR 的收敛速度提高了 6.7 倍；对于更强的骨干网络 DC5-R50 和 DC5-R101，收敛速度提高了 10 倍。代码可在 https://github.com/Atten4Vis/ConditionalDETR 获取。*

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

 Conditional DETR 与原始 DETR 相比，收敛速度显著更快。摘自原始论文。

该模型由 [DepuMeng](https://huggingface.co/DepuMeng) 贡献。原始代码可在[此处](https://github.com/Atten4Vis/ConditionalDETR)找到。

## 资源

- 另请参阅：[目标检测任务指南](../tasks/object_detection)。

## ConditionalDetrConfig[[transformers.ConditionalDetrConfig]]

#### transformers.ConditionalDetrConfig[[transformers.ConditionalDetrConfig]]

```python
transformers.ConditionalDetrConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, is_encoder_decoder: bool = True, backbone_config: dict | transformers.configuration_utils.PreTrainedConfig | None = None, num_channels: int = 3, num_queries: int = 300, encoder_layers: int = 6, encoder_ffn_dim: int = 2048, encoder_attention_heads: int = 8, decoder_layers: int = 6, decoder_ffn_dim: int = 2048, decoder_attention_heads: int = 8, encoder_layerdrop: float | int = 0.0, decoder_layerdrop: float | int = 0.0, activation_function: str = 'relu', d_model: int = 256, dropout: float | int = 0.1, attention_dropout: float | int = 0.0, activation_dropout: float | int = 0.0, init_std: float = 0.02, init_xavier_std: float = 1.0, auxiliary_loss: bool = False, position_embedding_type: str = 'sine', dilation: bool = False, class_cost: int = 2, bbox_cost: int = 5, giou_cost: int = 2, mask_loss_coefficient: int = 1, dice_loss_coefficient: int = 1, cls_loss_coefficient: int = 2, bbox_loss_coefficient: int = 5, giou_loss_coefficient: int = 2, focal_alpha: float = 0.25)
```

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

**参数：**

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

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

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

num_queries (`int`, *可选*，默认为 300)：对象查询的数量，即检测槽位。这是 [ConditionalDetrModel](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrModel) 在单张图像中可检测到的最大对象数量。对于 COCO，我们建议使用 100 个查询。

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

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

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

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

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

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

encoder_layerdrop (`Union[float, int]`，*可选*，默认为 `0.0`)：编码器的 LayerDrop 概率。有关更多详细信息，请参阅 [LayerDrop 论文](see https://huggingface.co/papers/1909.11556)。

decoder_layerdrop (`Union[float, int]`，*可选*，默认值为 `0.0`)：解码器的 LayerDrop 概率。有关更多详细信息，请参阅 [LayerDrop 论文](see https://huggingface.co/papers/1909.11556)。

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

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

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

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

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

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

init_xavier_std (`float`, *可选*，默认为 `1.0`) : 用于交叉注意力权重 Xavier 初始化的缩放因子。

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

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

dilation (`bool`，*可选*，默认为 `False`)：是否将最后一个卷积块（DC5）中的 stride 替换为 dilation。仅在 `use_timm_backbone` = `True` 时支持。

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

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

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

mask_loss_coefficient (`int`, *可选*，默认为 `1`)：全景分割损失中焦点损失的相对权重。

dice_loss_coefficient (`int`, *可选*, 默认为 `1`) : 全景分割损失中 dice loss 的相对权重。

cls_loss_coefficient (`int`, *可选*，默认为 `2`)：全景分割损失中分类损失的相对权重。

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

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

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

这是用于存储 ConditionalDetrModel 配置的类。它根据指定的参数实例化 Conditional Detr 模型，并定义模型架构。使用默认值实例化配置将生成与 [microsoft/conditional-detr-resnet-50](https://huggingface.co/microsoft/conditional-detr-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 ConditionalDetrConfig, ConditionalDetrModel

>>> # Initializing a Conditional DETR microsoft/conditional-detr-resnet-50 style configuration
>>> configuration = ConditionalDetrConfig()

>>> # Initializing a model (with random weights) from the microsoft/conditional-detr-resnet-50 style configuration
>>> model = ConditionalDetrModel(configuration)

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

## ConditionalDetrImageProcessor[[transformers.ConditionalDetrImageProcessor]]

#### transformers.ConditionalDetrImageProcessor[[transformers.ConditionalDetrImageProcessor]]

```python
transformers.ConditionalDetrImageProcessor(**kwargs: *<class 'transformers.models.conditional_detr.image_processing_conditional_detr.ConditionalDetrImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L428)

**参数：**

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

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

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

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认为 `2`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*，默认为 `True`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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

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

构建一个 ConditionalDetrImageProcessor 图像处理器。

#### preprocess[[transformers.ConditionalDetrImageProcessor.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.conditional_detr.image_processing_conditional_detr.ConditionalDetrImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/image_processing_conditional_detr.py#L683)

**参数：**

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`)：控制是否将注释转换为 CONDITIONAL_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 张量中的整数列表进行转换。

## ConditionalDetrImageProcessorPil[[transformers.ConditionalDetrImageProcessorPil]]

#### transformers.ConditionalDetrImageProcessorPil[[transformers.ConditionalDetrImageProcessorPil]]

```python
transformers.ConditionalDetrImageProcessorPil(**kwargs: *<class 'transformers.models.conditional_detr.image_processing_pil_conditional_detr.ConditionalDetrImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py#L429)

**参数：**

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

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

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

default_to_square (`bool`, *kwargs*, *可选*，默认为 `False`) : 当 size 为整数时，是否在调整大小时默认使用正方形图像。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 应用 `center_crop` 后输出图像的尺寸。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*，默认为 `2`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `PILImageResampling` 中的一个值。仅当 `do_resize` 设置为 `True` 时才会生效。

do_rescale (`bool`, *kwargs*, *可选*，默认为 `True`)：是否对图像进行重新缩放。

rescale_factor (`float`, *kwargs*, *可选*，默认为 `0.00392156862745098`) : 当 `do_rescale` 设置为 `True` 时，用于对图像进行缩放的缩放因子。

do_normalize (`bool`，*kwargs*，*可选*，默认为 `True`)：是否对图像进行归一化。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.485, 0.456, 0.406]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[0.229, 0.224, 0.225]`) : 用于归一化的图像标准差。仅当 `do_normalize` 设置为 `True` 时生效。

do_pad (`bool`, *kwargs*, *可选*，默认为 `True`) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : 用于将图像填充到的尺寸，格式为 `{"height": int, "width" int}`。该尺寸必须大于预处理中提供的任何图像尺寸。如果未提供 `pad_size`，图像将被填充到批次中最大的高度和宽度。仅在 `do_pad=True.` 时应用。

do_center_crop (`bool`, *kwargs*, *可选*) : 是否对图像进行居中裁剪。

data_format (`Union[str, ~image_utils.ChannelDimension]`，*kwargs*，*可选*)：仅支持 `ChannelDimension.FIRST`。为兼容旧版处理器而添加。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *可选*) : 输入图像的通道维度格式。如果未设置，则从输入图像中推断通道维度格式。可以是以下之一： - `"channels_first"` 或 `ChannelDimension.FIRST`：图像为 (num_channels, height, width) 格式。 - `"channels_last"` 或 `ChannelDimension.LAST`：图像为 (height, width, num_channels) 格式。 - `"none"` 或 `ChannelDimension.NONE`：图像为 (height, width) 格式。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*)：用于处理视频的设备。如果未设置，则从输入视频中推断设备。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : 如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

disable_grouping (`bool`, *kwargs*, *可选*) : 是否禁用按尺寸对图像进行分组，从而逐个处理图像而非批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详见此处：https://github.com/huggingface/transformers/pull/38157

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

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

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

构建一个 ConditionalDetrImageProcessor 图像处理器。

#### preprocess[[transformers.ConditionalDetrImageProcessorPil.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.conditional_detr.image_processing_pil_conditional_detr.ConditionalDetrImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py#L697)

**参数：**

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`)：控制是否将注释转换为 CONDITIONAL_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.ConditionalDetrImageProcessorPil.post_process_object_detection]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py#L842)

**参数：**

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

threshold (`float`, *可选*) : 用于保留目标检测预测结果的分数阈值。

target_sizes (`torch.Tensor` 或 `list[tuple[int, int]]`，*可选*)：形状为 `(batch_size, 2)` 的张量，或包含元组（`tuple[int, int]`）的列表，其中包含批次中每张图片的目标尺寸（高度、宽度）。如果设为 None，则不会调整预测结果的尺寸。

top_k (`int`，*可选*，默认为 100)：在通过阈值过滤之前，仅保留前 k 个边界框。

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

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

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

#### post_process_instance_segmentation[[transformers.ConditionalDetrImageProcessorPil.post_process_instance_segmentation]]

```python
post_process_instance_segmentation(outputs, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, target_sizes: list[tuple[int, int]] | None = None, return_coco_annotation: bool | None = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py#L974)

**参数：**

outputs ([ConditionalDetrForSegmentation](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation))：模型的原始输出。

threshold (`float`, *可选*，默认为 0.5)：用于保留预测实例掩码的概率分数阈值。

mask_threshold (`float`，*可选*，默认值为 0.5)：将预测掩码转换为二值时使用的阈值。

overlap_mask_area_threshold (`float`, *可选*，默认为 0.8)：用于合并或丢弃每个二值实例掩码内部小的不连通部分的重叠掩码面积阈值。

target_sizes (`list[Tuple]`，*可选*)：长度为 (batch_size) 的列表，其中每个列表项 (`tuple[int, int]]`) 对应每个预测所需的最终尺寸（高度、宽度）。如果未设置，则不会调整预测结果的尺寸。

return_coco_annotation (`bool`, *可选*) : 默认为 `False`。如果设置为 `True`，分割图将以 COCO 游程编码（RLE）格式返回。

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

一个字典列表，每张图片对应一个字典，每个字典包含两个键：
- **segmentation** -- A tensor of shape `(height, width)` where each pixel represents a `segment_id` or `list[List]` run-length encoding (RLE) of the segmentation map if return_coco_annotation is set to `True`. Set to `None` if no mask if found above `threshold`.
- **segments_info** -- 一个包含每个片段附加信息的字典。
  - **id** -- 一个表示 `segment_id` 的整数。
  - **label_id** -- 一个整数，表示与 `segment_id` 对应的标签/语义类别 ID。
  - **score** -- 具有 `segment_id` 的片段的预测分数。

将 [ConditionalDetrForSegmentation](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) 的输出转换为实例分割预测。仅支持 PyTorch。

#### post_process_semantic_segmentation[[transformers.ConditionalDetrImageProcessorPil.post_process_semantic_segmentation]]

```python
post_process_semantic_segmentation(outputs, target_sizes: list[tuple[int, int]] | None = None, return_segmentation_scores: bool = False)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py#L902)

**参数：**

outputs ([ConditionalDetrForSegmentation](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation))：模型的原始输出。

target_sizes (`list[tuple[int, int]]`，*可选*)：一个元组列表（`tuple[int, int]`），包含批处理中每张图片的目标尺寸（高度、宽度）。如果未设置，预测结果将不会被调整大小。

return_segmentation_scores (`bool`，*可选*，默认为 `False`)：是否同时返回分割分数和分割图。当为 `True` 时，返回列表中的每个元素都是一个 `SemanticSegmentationPostProcessorOutput`，包含字段 `segmentation`（类别 ID，形状为 `(height, width)`）和 `segmentation_scores`（形状为 `(num_classes, height, width)`）。

**返回：** `list[torch.Tensor]` 或 `list[SemanticSegmentationPostProcessorOutput]`

当 `return_segmentation_scores=False`（默认值）时，返回一个长度为 `batch_size` 的列表，其中每个元素都是形状为 `(height, width)` 且包含类别 ID 的分割图。当 `return_segmentation_scores=True` 时，返回一个 `SemanticSegmentationPostProcessorOutput` 列表，包含字段 `segmentation`（类别 ID，形状为 `(height, width)`）和 `segmentation_scores`（形状为 `(num_classes, height, width)`）。在这两种情况下，`(height, width)` 均对应目标尺寸（如果指定了 `target_sizes`）。

将 [ConditionalDetrForSegmentation](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) 的输出转换为语义分割图。仅支持 PyTorch。

#### post_process_panoptic_segmentation[[transformers.ConditionalDetrImageProcessorPil.post_process_panoptic_segmentation]]

```python
post_process_panoptic_segmentation(outputs, threshold: float = 0.5, mask_threshold: float = 0.5, overlap_mask_area_threshold: float = 0.8, label_ids_to_fuse: set[int] | None = None, target_sizes: list[tuple[int, int]] | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/image_processing_pil_conditional_detr.py#L1058)

**参数：**

outputs ([ConditionalDetrForSegmentation](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation))：[ConditionalDetrForSegmentation](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) 的输出。

threshold (`float`, *可选*，默认为 0.5)：用于保留预测实例掩码的概率分数阈值。

mask_threshold (`float`，*可选*，默认值为 0.5)：将预测掩码转换为二值时使用的阈值。

overlap_mask_area_threshold (`float`, *可选*，默认为 0.8)：用于合并或丢弃每个二值实例掩码内部小的不连通部分的重叠掩码面积阈值。

label_ids_to_fuse (`Set[int]`, *可选*) : 在此状态下，标签的所有实例将被融合在一起。例如，我们可以说一张图像中只能有一个天空，但可以有多个行人，因此天空的标签 ID 会包含在该集合中，而行人的标签 ID 则不会。

target_sizes (`list[Tuple]`，*可选*)：长度为 (batch_size) 的列表，其中每个列表项 (`tuple[int, int]]`) 对应批处理中每个预测所需的最终尺寸（高度、宽度）。如果未设置，则不会调整预测结果的尺寸。

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

一个字典列表，每张图片对应一个字典，每个字典包含两个键：
- **segmentation** -- 形状为 `(height, width)` 的张量，其中每个像素表示一个 `segment_id`，或者在未找到高于 `threshold` 的掩码时为 `None`。如果指定了 `target_sizes`，则 segmentation 会被调整大小以对应 `target_sizes` 中的相应条目。
- **segments_info** -- 一个包含每个片段附加信息的字典。
  - **id** -- 一个表示 `segment_id` 的整数。
  - **label_id** -- 一个整数，表示与 `segment_id` 对应的标签/语义类别 ID。
  - **was_fused** -- 一个布尔值，如果 `label_id` 在 `label_ids_to_fuse` 中，则为 `True`，否则为 `False`。同一类别/标签的多个实例已被融合，并被分配了单一的 `segment_id`。
  - **score** -- 具有 `segment_id` 的片段的预测分数。

将 [ConditionalDetrForSegmentation](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) 的输出转换为图像全景分割预测。仅支持 PyTorch。

## ConditionalDetrModel[[transformers.ConditionalDetrModel]]

#### transformers.ConditionalDetrModel[[transformers.ConditionalDetrModel]]

```python
transformers.ConditionalDetrModel(config: ConditionalDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1336)

**参数：**

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

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

该模型继承自 [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.ConditionalDetrModel.forward]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1365)

**参数：**

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)

decoder_attention_mask (`torch.Tensor`，形状为 `(batch_size, num_queries)`，*可选*)：默认情况下不使用。可用于对对象查询进行掩码处理。

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 + 投影层的输出）外，你还可以选择直接传入图像的展平表示。

decoder_inputs_embeds (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是用零张量来初始化查询。

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

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

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型解码器最后一层输出的隐藏状态序列。

  如果使用了`cache`，则仅输出形状为`(batch_size, 1, hidden_size)`的序列的最后一个隐藏状态。
- **cache** (`EncoderDecoderCache`，*可选*，在传入 `use_cache=True` 或 `config.use_cache=True` 时返回) -- 它是一个 [EncoderDecoderCache](/docs/transformers/main/zh/internal/generation_utils#transformers.EncoderDecoderCache) 实例。有关更多详细信息，请参阅我们的 [kv cache 指南](https://huggingface.co/docs/transformers/en/kv_cache)。

  包含预计算的隐藏状态（自注意力块和交叉注意力块中的键和值），可用于（参见 `cache` 输入）加速顺序解码。
- **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 之后的注意力权重，用于在自注意力头中计算加权平均值。
- **intermediate_hidden_states**（形状为 `(config.decoder_layers, batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`，*可选*，当 `config.auxiliary_loss=True` 时返回）-- 中间解码器激活值，即每个解码器层的输出，且每个输出都经过了层归一化。
- **reference_points**（形状为 `(config.decoder_layers, batch_size, num_queries, 2 (anchor points))` 的 `torch.Tensor`）-- 参考点（解码器每一层的参考点）。

示例：

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

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

>>> image_processor = AutoImageProcessor.from_pretrained("microsoft/conditional-detr-resnet-50")
>>> model = AutoModel.from_pretrained("microsoft/conditional-detr-resnet-50")

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

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

>>> # the last hidden states are the final query embeddings of the Transformer decoder
>>> # these are of shape (batch_size, num_queries, hidden_size)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 300, 256]
```

## ConditionalDetrForObjectDetection[[transformers.ConditionalDetrForObjectDetection]]

#### transformers.ConditionalDetrForObjectDetection[[transformers.ConditionalDetrForObjectDetection]]

```python
transformers.ConditionalDetrForObjectDetection(config: ConditionalDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1508)

**参数：**

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

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

该模型继承自 [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.ConditionalDetrForObjectDetection.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.LongTensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, decoder_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/conditional_detr/modeling_conditional_detr.py#L1522)

**参数：**

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)

decoder_attention_mask (`torch.Tensor`，形状为 `(batch_size, num_queries)`，*可选*)：默认情况下不使用。可用于对对象查询进行掩码处理。

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 + 投影层的输出）外，你还可以选择直接传入图像的展平表示。

decoder_inputs_embeds (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_size)`，*可选*)：可选地，你可以选择直接传入嵌入表示，而不是用零张量来初始化查询。

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

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

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

[ConditionalDetrForObjectDetection](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForObjectDetection) 的 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()` 来获取未归一化的边界框。
- **auxiliary_outputs** (`list[Dict]`, *可选*) -- 可选，仅在启用辅助损失（即 `config.auxiliary_loss` 设置为 `True`）且提供了标签时返回。它是一个字典列表，包含每个解码器层的上述两个键（`logits` 和 `pred_boxes`）。
- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `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 之后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
>>> 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("microsoft/conditional-detr-resnet-50")
>>> model = AutoModelForObjectDetection.from_pretrained("microsoft/conditional-detr-resnet-50")

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

>>> outputs = model(**inputs)

>>> # 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.5, 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 remote with confidence 0.833 at location [38.31, 72.1, 177.63, 118.45]
Detected cat with confidence 0.831 at location [9.2, 51.38, 321.13, 469.0]
Detected cat with confidence 0.804 at location [340.3, 16.85, 642.93, 370.95]
Detected remote with confidence 0.683 at location [334.48, 73.49, 366.37, 190.01]
Detected couch with confidence 0.535 at location [0.52, 1.19, 640.35, 475.1]
```

## ConditionalDetrForSegmentation[[transformers.ConditionalDetrForSegmentation]]

#### transformers.ConditionalDetrForSegmentation[[transformers.ConditionalDetrForSegmentation]]

```python
transformers.ConditionalDetrForSegmentation(config: ConditionalDetrConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/conditional_detr/modeling_conditional_detr.py#L1649)

**参数：**

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

用于 COCO 全景分割等任务的 CONDITIONAL_DETR 模型（由骨干网络和编码器-解码器 Transformer 组成），并在其上方添加分割头。

该模型继承自 [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.ConditionalDetrForSegmentation.forward]]

```python
forward(pixel_values: Tensor, pixel_mask: typing.Optional[torch.LongTensor] = None, decoder_attention_mask: typing.Optional[torch.Tensor] = None, encoder_outputs: typing.Optional[torch.Tensor] = None, inputs_embeds: typing.Optional[torch.Tensor] = None, decoder_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/conditional_detr/modeling_conditional_detr.py#L1671)

**参数：**

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)

decoder_attention_mask (`torch.Tensor`，形状为 `(batch_size, num_queries)`，*可选*) : 用于避免在解码器中对某些对象查询执行注意力的掩码。掩码值选自 `[0, 1]`： - 对于**未掩码**的查询，值为 1； - 对于**已掩码**的查询，值为 0。

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)`，*可选*)：为保持向后兼容性而保留，但无法用于分割，因为分割需要来自骨干网络的多尺度特征，而使用 inputs_embeds 绕过骨干网络时无法获取这些特征。

decoder_inputs_embeds (`torch.Tensor`，形状为 `(batch_size, num_queries, hidden_size)`，*可选*)：可选地，您可以选择直接传入嵌入表示，而不是用零张量来初始化查询。这对于需要自定义查询初始化的任务非常有用。

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

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

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

[ConditionalDetrForSegmentation](/docs/transformers/main/zh/model_doc/conditional_detr#transformers.ConditionalDetrForSegmentation) 的 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()` 来获取未归一化的边界框。
- **pred_masks**（形状为 `(batch_size, num_queries, height/4, width/4)` 的 `torch.Tensor`）-- 所有查询的分割掩码 logits。请参阅 `post_process_semantic_segmentation()` 或 `post_process_instance_segmentation()` `post_process_panoptic_segmentation()`，分别用于评估语义、实例和全景分割掩码。
- **auxiliary_outputs** (`list[Dict]`, *可选*) -- 可选，仅在启用辅助损失（即 `config.auxiliary_loss` 设置为 `True`）且提供了标签时返回。它是一个字典列表，包含每个解码器层的上述两个键（`logits` 和 `pred_boxes`）。
- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `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 之后的注意力权重，用于在自注意力头中计算加权平均值。

示例：

```python
>>> import io
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> from PIL import Image
>>> import torch
>>> import numpy

>>> from transformers import AutoImageProcessor, ConditionalDetrForSegmentation
>>> from transformers.image_transforms import rgb_to_id

>>> 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("facebook/conditional_detr-resnet-50-panoptic")
>>> model = ConditionalDetrForSegmentation.from_pretrained("facebook/conditional_detr-resnet-50-panoptic")

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

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

>>> # Use the `post_process_panoptic_segmentation` method of the `image_processor` to retrieve post-processed panoptic segmentation maps
>>> # Segmentation results are returned as a list of dictionaries
>>> result = image_processor.post_process_panoptic_segmentation(outputs, target_sizes=[(300, 500)])

>>> # A tensor of shape (height, width) where each value denotes a segment id, filled with -1 if no segment is found
>>> panoptic_seg = result[0]["segmentation"]
>>> panoptic_seg.shape
torch.Size([300, 500])
>>> # Get prediction score and segment_id to class_id mapping of each segment
>>> panoptic_segments_info = result[0]["segments_info"]
>>> len(panoptic_segments_info)
5
```

