# PP-DocLayoutV2

## 概述

**PP-DocLayoutV2** 是一款专为版面分析设计的轻量级模型，专注于元素检测、分类以及阅读顺序预测。

## 模型架构

PP-DocLayoutV2 由两个顺序连接的网络组成。第一个是基于 RT-DETR 的检测模型，用于执行版面元素检测和分类。随后，检测到的边界框和类别标签会被传递到一个指针网络（pointer network），由该网络负责对这些版面元素进行排序。

## 用法

### 单输入推理

以下示例演示了如何使用 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel) 通过 PP-DocLayoutV2 生成文本。

```python
import requests
from PIL import Image

from transformers import pipeline

image = Image.open(requests.get("https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/paddle_layout_demo.jpg", stream=True).raw)
layout_detector = pipeline("object-detection", model="PaddlePaddle/PP-DocLayoutV2_safetensors")
result = layout_detector(image)
print(result)
```

```python
import requests
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForObjectDetection

model_path = "PaddlePaddle/PP-DocLayoutV2_safetensors"
model = AutoModelForObjectDetection.from_pretrained(model_path, device_map="auto")
image_processor = AutoImageProcessor.from_pretrained(model_path)
image = Image.open(requests.get("https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/paddle_layout_demo.jpg", stream=True).raw)
inputs = image_processor(images=image, return_tensors="pt").to(model.device)

outputs = model(**inputs)
results = image_processor.post_process_object_detection(outputs, target_sizes=[image.size[::-1]])
for result in results:
    print(result["scores"])
    print(result["labels"])
    print(result["boxes"])
    for idx, (score, label_id, box) in enumerate(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"Order {idx + 1}: {model.config.id2label[label]}: {score:.2f} {box}")
```

### 批量推理

以下是使用 PP-DocLayoutV2 通过 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel) 实现的方法：

```python
import requests
from PIL import Image

from transformers import pipeline

image = Image.open(requests.get("https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/paddle_layout_demo.jpg", stream=True).raw)
layout_detector = pipeline("object-detection", model="PaddlePaddle/PP-DocLayoutV2_safetensors")
result = layout_detector([image, image])
print(result[0])
print(result[1])
```

```python
import requests
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForObjectDetection

model_path = "PaddlePaddle/PP-DocLayoutV2_safetensors"
model = AutoModelForObjectDetection.from_pretrained(model_path, device_map="auto")
image_processor = AutoImageProcessor.from_pretrained(model_path)

image = Image.open(requests.get("https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/paddle_layout_demo.jpg", stream=True).raw)
inputs = image_processor(images=[image, image], return_tensors="pt").to(model.device)
target_sizes = [image.size[::-1], image.size[::-1]]

outputs = model(**inputs)
results = image_processor.post_process_object_detection(outputs, target_sizes=target_sizes)
for result in results:
    print("result:")
    for idx, (score, label_id, box) in enumerate(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"Order {idx + 1}: {model.config.id2label[label]}: {score:.2f} {box}")
```

## PPDocLayoutV2Config[[transformers.PPDocLayoutV2Config]]

#### transformers.PPDocLayoutV2Config[[transformers.PPDocLayoutV2Config]]

```python
transformers.PPDocLayoutV2Config(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: transformers.configuration_utils.PreTrainedConfig | dict | None = None, freeze_backbone_batch_norms: bool = True, encoder_hidden_dim: int = 256, encoder_in_channels: list[int] | tuple[int, ...] | None = (512, 1024, 2048), feat_strides: list[int] | tuple[int, ...] | None = (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, ...] | None = (2,), positional_encoding_temperature: int = 10000, encoder_activation_function: str = 'gelu', activation_function: str = 'silu', eval_size: list[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, ...] | None = (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: list[int] | None = None, disable_custom_kernels: bool = True, class_thresholds: list[float] | None = None, class_order: list[int] | None = None, reading_order_config: transformers.configuration_utils.PreTrainedConfig | dict | None = None)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pp_doclayout_v2/configuration_pp_doclayout_v2.py#L106)

**参数：**

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[~configuration_utils.PreTrainedConfig, dict]`, *可选*) : 骨干模型的配置。

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)：编码器使用的总层数。

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`)：是否禁用自定义内核。

class_thresholds (`list[float]`, *可选*) : 每个标签的阈值。

class_order (`list[int]`, *可选*) : 每个标签的优先级。

reading_order_config (`dict`, *可选*) : `PPDocLayoutV2ReadingOrder` 的配置。

这是用于存储 Pp Doclayout V2Model 配置的类。它根据指定的参数实例化 Pp Doclayout V2 模型，并定义模型架构。使用默认值实例化配置将得到与 [PaddlePaddle/PP-DocLayoutV2_safetensors](https://huggingface.co/PaddlePaddle/PP-DocLayoutV2_safetensors) 类似的配置。

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

示例：

```python
>>> from transformers import PPDocLayoutV2Config, PPDocLayoutV2ForObjectDetection

>>> # Initializing a PP-DocLayoutV2 configuration
>>> configuration = PPDocLayoutV2Config()

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

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

## PPDocLayoutV2ForObjectDetection[[transformers.PPDocLayoutV2ForObjectDetection]]

#### transformers.PPDocLayoutV2ForObjectDetection[[transformers.PPDocLayoutV2ForObjectDetection]]

```python
transformers.PPDocLayoutV2ForObjectDetection(config: PPDocLayoutV2Config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py#L2342)

**参数：**

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

PP-DocLayoutV2 模型（由骨干网络和编码器-解码器组成）输出边界框、logits 和 order_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.PPDocLayoutV2ForObjectDetection.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, 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/pp_doclayout_v2/modeling_pp_doclayout_v2.py#L2368)

**参数：**

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

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

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

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

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

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

- **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) 来获取未归一化（绝对）的边界框。
- **order_logits** (`tuple` of `torch.Tensor` of shape `(batch_size, num_queries, num_queries)`) -- Order logits for all queries. The first dimension of each tensor is the batch size. The second dimension is the number of queries.
- **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 AutoModelForObjectDetection, AutoImageProcessor
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO
>>> import torch

>>> url = "https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/paddle_layout_demo.jpg"
>>> with httpx.stream("GET", url) as response:
...     image = Image.open(BytesIO(response.read()))

>>> model_path = "PaddlePaddle/PP-DocLayoutV2_safetensors"
>>> image_processor = AutoImageProcessor.from_pretrained(model_path)
>>> model = AutoModelForObjectDetection.from_pretrained(model_path)

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

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

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

>>> # print outputs
>>> for result in results:
...     for idx, (score, label_id, box) in enumerate(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"Order {idx + 1}: {model.config.id2label[label]}: {score:.2f} {box}")
Order 1: text: 0.99 [335.39, 184.26, 896.49, 654.48]
Order 2: paragraph_title: 0.97 [337.14, 683.49, 869.42, 798.27]
Order 3: text: 0.99 [335.71, 843.04, 891.17, 1454.15]
Order 4: text: 0.99 [920.42, 185.53, 1476.39, 464.25]
Order 5: text: 0.98 [920.62, 483.75, 1480.52, 765.34]
Order 6: text: 0.98 [920.58, 846.75, 1481.94, 1220.53]
Order 7: text: 0.97 [921.12, 1239.27, 1468.87, 1377.33]
Order 8: footnote: 0.82 [334.58, 1614.67, 1483.84, 1731.61]
Order 9: text: 0.51 [334.58, 1614.67, 1483.84, 1731.61]
Order 10: footnote: 0.83 [334.7, 1757.26, 1471.07, 1845.33]
Order 11: text: 0.87 [336.65, 1910.28, 661.33, 1939.92]
Order 12: footnote: 0.95 [336.16, 2114.52, 1450.28, 2171.74]
Order 13: number: 0.87 [106.04, 2257.37, 136.05, 2281.98]
Order 14: footer: 0.93 [338.6, 2255.94, 985.67, 2283.57]
```

## PPDocLayoutV2Model[[transformers.PPDocLayoutV2Model]]

#### transformers.PPDocLayoutV2Model[[transformers.PPDocLayoutV2Model]]

```python
transformers.PPDocLayoutV2Model(config: PPDocLayoutV2Config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py#L2015)

**参数：**

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

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

该模型继承自 [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.PPDocLayoutV2Model.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/pp_doclayout_v2/modeling_pp_doclayout_v2.py#L2136)

**参数：**

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

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

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

[PPDocLayoutV2Model](/docs/transformers/main/zh/model_doc/pp_doclayout_v2#transformers.PPDocLayoutV2Model) 的 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, PPDocLayoutV2Model
>>> 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/PPDocLayoutV2_r50vd")
>>> model = PPDocLayoutV2Model.from_pretrained("PekingU/PPDocLayoutV2_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]
```

## PPDocLayoutV2ReadingOrder[[transformers.PPDocLayoutV2ReadingOrder]]

#### transformers.PPDocLayoutV2ReadingOrder[[transformers.PPDocLayoutV2ReadingOrder]]

```python
transformers.PPDocLayoutV2ReadingOrder(config: PPDocLayoutV2Config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py#L803)

**参数：**

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

PP-DocLayoutV2 ReadingOrder 模型。该模型由一个编码器和一个 GlobalPointer 头组成。它以布局特征作为输入，输出表示元素之间相对顺序关系的 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.PPDocLayoutV2ReadingOrder.forward]]

```python
forward(boxes, labels = None, mask = None, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pp_doclayout_v2/modeling_pp_doclayout_v2.py#L821)

**参数：**

boxes (`torch.Tensor`，形状为 `(batch_size, sequence_length, 4)`)：检测到的布局元素的边界框坐标，**采用 [0, 1000] 尺度**。格式为 `[x_min, y_min, x_max, y_max]`。该张量通常包含排序后的有效边界框，后接零填充。

labels (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*) : 每个布局元素的**重映射**类别索引。这些不一定是原始检测类别 ID，而是通过 `config.class_order` 映射得到的索引（例如，将 text/title/figure 映射到特定的阅读顺序类别 ID）。

mask (`torch.Tensor`，形状为 `(batch_size, sequence_length)`，*可选*) : 布尔型或二进制掩码，指示阈值过滤后有效的检测元素。- True：有效的布局元素。- False：填充/空元素。用于确定指针机制的序列长度（`num_pred`）。

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

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

## PPDocLayoutV2ImageProcessor[[transformers.PPDocLayoutV2ImageProcessor]]

#### transformers.PPDocLayoutV2ImageProcessor[[transformers.PPDocLayoutV2ImageProcessor]]

```python
transformers.PPDocLayoutV2ImageProcessor(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/pp_doclayout_v2/image_processing_pp_doclayout_v2.py#L34)

**参数：**

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' : 800, 'width': 800}`)：描述输入到模型的最大尺寸。

default_to_square (`bool`，*kwargs*，*可选*，默认为 `True`)：当 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*，默认值为 `3`) : 如果调整图像大小，则使用的重采样滤波器。它可以是枚举 `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, 0, 0]`) : 用于归一化的图像均值。仅当 `do_normalize` 设置为 `True` 时生效。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *可选*，默认为 `[1, 1, 1]`) : 用于归一化的图像标准差。仅当 `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*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*，默认值为 `256`) : 输入中每张图片所使用的图像 token 数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

image_seq_length (`int`, *kwargs*, *可选*) : 输入中每张图片所使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器属性。如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。

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

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

如果设置为 `'pt'`，则返回堆叠的张量，否则返回张量列表。 --

构建一个 PPDocLayoutV2ImageProcessor 图像处理器。

disable_grouping (`bool`, *kwargs*, *可选*)：是否禁用按大小对图像进行分组，以便单独处理图像而不是批量处理。如果为 None，则当图像位于 CPU 上时设置为 True，否则设置为 False。此选择基于经验观察，详情见此处：https://github.com/huggingface/transformers/pull/38157 image_seq_length (`int`, *kwargs*, *可选*)：输入中每张图像要使用的图像标记数量。为向后兼容而添加，但在未来的模型中应将其设置为处理器的属性。

#### preprocess[[transformers.PPDocLayoutV2ImageProcessor.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']], *args, image_like_kwargs: dict[str, typing.Any] | None = None, **kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/image_processing_utils.py#L382)

**参数：**

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

image_like_kwargs (`dict[str, Any]`，*可选*)：用于额外图像类输入的开发者标志，这些输入也将被预处理。仅在以关键字参数传递输入不起作用时使用此标志。例如，`preprocess(images, masks=masks)` 是首选方式，但对于某些模型会导致参数优先级问题。在这种情况下，可以改用 `preprocess(images, image_like_inputs={"masks": masks})`。

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 数量。为向后兼容而添加，但在未来的模型中，应将其设置为处理器的属性。

**返回：** `~image_processing_base.BatchFeature`

- **data** (`dict`) -- 由 __call__ 方法返回的列表/数组/张量字典（例如 'pixel_values'）。
- **tensor_type** (`Union[None, str, TensorType]`，*可选*) -- 您可以在此处指定 tensor_type，以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

预处理一张图像或一批图像。

