# SegFormer

[SegFormer: Simple and Efficient Design for Semantic Segmentation with Transformers](https://huggingface.co/papers/2105.15203) is a semantic segmentation model that combines a hierarchical Transformer encoder (Mix Transformer, MiT) with a lightweight all-MLP decoder. It avoids positional encodings and complex decoders and achieves state-of-the-art performance on benchmarks like ADE20K and Cityscapes. This simple and lightweight design is more efficient and scalable.

下图展示了 SegFormer 的架构。

您可以在 [NVIDIA](https://huggingface.co/nvidia/models?search=segformer) 组织下找到所有原始的 SegFormer 检查点。

> [!TIP]
> 该模型由 [nielsr](https://huggingface.co/nielsr) 贡献。
>
> 点击右侧边栏中的 SegFormer 模型，以查看将 SegFormer 应用于不同视觉任务的更多示例。

以下示例演示了如何使用 [Pipeline](/docs/transformers/main/zh/main_classes/pipelines#transformers.Pipeline) 或 [AutoModel](/docs/transformers/main/zh/model_doc/auto#transformers.AutoModel) 类进行语义分割。

```python
from transformers import pipeline

pipeline = pipeline(task="image-segmentation", model="nvidia/segformer-b0-finetuned-ade-512-512")
pipeline("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")
```

```python
import requests
from PIL import Image

from transformers import AutoModelForSemanticSegmentation, AutoProcessor

url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
image = Image.open(requests.get(url, stream=True).raw)

processor = AutoProcessor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
model = AutoModelForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512", device_map="auto")

inputs = processor(images=image, return_tensors="pt").to(model.device)
outputs = model(**inputs)
logits = outputs.logits # shape [batch, num_labels, height, width]
```

## 备注

- SegFormer 支持**任意输入尺寸**，会将输入填充为可被 `config.patch_sizes` 整除的尺寸。
- 最重要的预处理步骤是随机裁剪并填充所有图像至相同尺寸（例如 512x512 或 640x640），然后进行归一化。
- 某些数据集（ADE20k）在标注的分割图中使用 `0` 索引作为背景，但其标签中并不包含“background”类别。`SegformerForImageProcessor` 中的 `do_reduce_labels` 参数用于将所有标签减少 `1`。为了确保不为背景类别计算损失，它会将标注图中的 `0` 替换为 `255`，即损失函数的 `ignore_index`。

   不过，其他数据集可能包含背景类别和标签，在这种情况下，`do_reduce_labels` 应设为 `False`。

```python
from transformers import SegformerImageProcessor

processor = SegformerImageProcessor(do_reduce_labels=True)
```

## 资源

- [原始 SegFormer 代码（NVlabs）](https://github.com/NVlabs/SegFormer)
- [微调博客文章](https://huggingface.co/blog/fine-tune-segformer)
- [教程笔记本（Niels Rogge）](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/SegFormer)
- [Hugging Face 演示空间](https://huggingface.co/spaces/chansung/segformer-tf-transformers)

## SegformerConfig[[transformers.SegformerConfig]]

#### transformers.SegformerConfig[[transformers.SegformerConfig]]

```python
transformers.SegformerConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, num_channels: int = 3, num_encoder_blocks: int = 4, depths: list[int] | tuple[int, ...] = (2, 2, 2, 2), sr_ratios: list[int] | tuple[int, ...] = (8, 4, 2, 1), hidden_sizes: list[int] | tuple[int, ...] = (32, 64, 160, 256), patch_sizes: list[int] | tuple[int, ...] = (7, 3, 3, 3), strides: list[int] | tuple[int, ...] = (4, 2, 2, 2), num_attention_heads: list[int] | tuple[int, ...] = (1, 2, 5, 8), mlp_ratios: list[int] | tuple[int, ...] = (4, 4, 4, 4), hidden_act: str = 'gelu', hidden_dropout_prob: float | int = 0.0, attention_probs_dropout_prob: float | int = 0.0, classifier_dropout_prob: float | int = 0.1, initializer_range: float = 0.02, drop_path_rate: float | int = 0.1, layer_norm_eps: float = 1e-06, decoder_hidden_size: int = 256, semantic_loss_ignore_index: int = 255, reshape_last_stage: bool = True)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/configuration_segformer.py#L24)

**参数：**

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

num_encoder_blocks (`int`, *可选*，默认为 4)：编码器块的数量（即 Mix Transformer 编码器中的阶段数）。

depths (`list[int]`，*可选*，默认为 `[2, 2, 2, 2]`)：每个编码器块中的层数。

sr_ratios (`list[int]`，*可选*，默认为 `[8, 4, 2, 1]`)：每个编码器块中的序列缩减比例。

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

patch_sizes (`list[int]`，*可选*，默认为 `[7, 3, 3, 3]`)：每个编码器块之前的补丁大小。

strides (`list[int]`，*可选*，默认为 `[4, 2, 2, 2]`)：每个编码器块之前的步长。

num_attention_heads (`Union[list[int], tuple[int, ...]]`，*可选*，默认为 `(1, 2, 5, 8)`)：Transformer 解码器中每个注意力层的注意力头数量。

mlp_ratios (`list[int]`，*可选*，默认为 `[4, 4, 4, 4]`)：编码器块中 Mix FFN 的隐藏层大小与输入层大小的比例。

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

hidden_dropout_prob (`Union[float, int]`，*可选*，默认值为 `0.0`)：嵌入层、编码器和池化器中所有全连接层的 dropout 概率。

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

classifier_dropout_prob (`Union[float, int]`，*可选*，默认为 `0.1`)：分类器的 dropout 比率。

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

drop_path_rate (`Union[float, int]`，*可选*，默认为 `0.1`)：用于 patch 融合的 drop path 比率。

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

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

semantic_loss_ignore_index (`int`，*可选*，默认为 `255`)：语义分割模型的损失函数所忽略的索引。

reshape_last_stage (`bool`, *可选*, 默认为 True) : 是否重塑最后一个阶段的输出

这是用于存储 SegformerModel 配置的类。它根据指定的参数实例化 Segformer 模型，并定义模型架构。使用默认值实例化配置将生成与 [ByteDance-Seed/Seed-OSS-36B-Instruct](https://huggingface.co/ByteDance-Seed/Seed-OSS-36B-Instruct) 类似的配置。

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

示例：

```python
>>> from transformers import SegformerModel, SegformerConfig

>>> # Initializing a SegFormer nvidia/segformer-b0-finetuned-ade-512-512 style configuration
>>> configuration = SegformerConfig()

>>> # Initializing a model from the nvidia/segformer-b0-finetuned-ade-512-512 style configuration
>>> model = SegformerModel(configuration)

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

## SegformerImageProcessor[[transformers.SegformerImageProcessor]]

#### transformers.SegformerImageProcessor[[transformers.SegformerImageProcessor]]

```python
transformers.SegformerImageProcessor(**kwargs: *<class 'transformers.models.segformer.image_processing_segformer.SegformerImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/image_processing_segformer.py#L55)

**参数：**

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

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `None`) : 应用 `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*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

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*, *可选*，默认为 `None`) : 是否对图像进行居中裁剪。

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

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `self.do_reduce_labels`) : 是否将所有分割图的标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集（例如 ADE20k）。背景标签将被替换为 255。

构建一个 SegformerImageProcessor 图像处理器。

#### preprocess[[transformers.SegformerImageProcessor.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']], segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.segformer.image_processing_segformer.SegformerImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/image_processing_segformer.py#L75)

**参数：**

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

segmentation_maps (`ImageInput`，*可选*)：要预处理的分割图。

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

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `self.do_reduce_labels`) : 是否将所有分割图的标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集（例如 ADE20k）。背景标签将被替换为 255。

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

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

#### post_process_semantic_segmentation[[transformers.SegformerImageProcessor.post_process_semantic_segmentation]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/image_processing_segformer.py#L192)

**参数：**

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

target_sizes (`list[Tuple]`，长度为 `batch_size`，*可选*) : 与每个预测所需的最终尺寸（高度、宽度）对应的元组列表。如果未设置，预测结果将不会被调整大小。

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

将 [SegformerForSemanticSegmentation](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerForSemanticSegmentation) 的输出转换为语义分割图。

## SegformerImageProcessorPil[[transformers.SegformerImageProcessorPil]]

#### transformers.SegformerImageProcessorPil[[transformers.SegformerImageProcessorPil]]

```python
transformers.SegformerImageProcessorPil(**kwargs: *<class 'transformers.models.segformer.image_processing_pil_segformer.SegformerImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/image_processing_pil_segformer.py#L56)

**参数：**

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

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

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*，默认为 `None`) : 应用 `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*, *可选*) : 是否对图像进行填充。填充操作会将图像填充至批次中的最大尺寸，或填充至每张图像的固定正方形尺寸。具体的填充策略取决于模型。

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*, *可选*，默认为 `None`) : 是否对图像进行居中裁剪。

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

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `self.do_reduce_labels`) : 是否将所有分割图的标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集（例如 ADE20k）。背景标签将被替换为 255。

构建一个 SegformerImageProcessor 图像处理器。

#### preprocess[[transformers.SegformerImageProcessorPil.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']], segmentation_maps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor'], NoneType] = None, **kwargs: *<class 'transformers.models.segformer.image_processing_pil_segformer.SegformerImageProcessorKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/image_processing_pil_segformer.py#L76)

**参数：**

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

segmentation_maps (`ImageInput`，*可选*)：要预处理的分割图。

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

do_reduce_labels (`bool`, *kwargs*, *可选*，默认为 `self.do_reduce_labels`) : 是否将所有分割图的标签值减 1。通常用于 0 表示背景且背景本身不包含在数据集所有类别中的数据集（例如 ADE20k）。背景标签将被替换为 255。

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

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

#### post_process_semantic_segmentation[[transformers.SegformerImageProcessorPil.post_process_semantic_segmentation]]

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/image_processing_pil_segformer.py#L175)

**参数：**

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

target_sizes (`list[Tuple]`，长度为 `batch_size`，*可选*) : 与每个预测所需的最终尺寸（高度、宽度）对应的元组列表。如果未设置，预测结果将不会被调整大小。

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

将 [SegformerForSemanticSegmentation](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerForSemanticSegmentation) 的输出转换为语义分割图。

## SegformerModel[[transformers.SegformerModel]]

#### transformers.SegformerModel[[transformers.SegformerModel]]

```python
transformers.SegformerModel(config: SegformerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/modeling_segformer.py#L376)

**参数：**

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

输出原始隐藏状态且顶部未附加任何特定头部的裸 Segformer 模型。

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

```python
forward(pixel_values: Tensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/modeling_segformer.py#L390)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [SegformerImageProcessor](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerImageProcessor) 获取像素值。有关详细信息，请参阅 [SegformerImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [SegformerImageProcessor](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerImageProcessor) 处理图像）。

**返回：** [BaseModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutput) 或 `tuple(torch.Tensor)`

一个 [BaseModelOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.BaseModelOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[SegformerConfig](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerConfig)）和输入。

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

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

- **last_hidden_state**（形状为 `(batch_size, sequence_length, hidden_size)` 的 `torch.Tensor`）-- 模型最后一层输出的隐藏状态序列。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层的输出，以及每一层的输出），形状为 `(batch_size, sequence_length, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, sequence_length, sequence_length)`。

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

示例：

```python
```

## SegformerDecodeHead[[transformers.SegformerDecodeHead]]

#### transformers.SegformerDecodeHead[[transformers.SegformerDecodeHead]]

```python
transformers.SegformerDecodeHead(config)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/modeling_segformer.py#L472)

#### forward[[transformers.SegformerDecodeHead.forward]]

```python
forward(encoder_hidden_states: Tensor, **kwargs)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/modeling_segformer.py#L496)

## SegformerForImageClassification[[transformers.SegformerForImageClassification]]

#### transformers.SegformerForImageClassification[[transformers.SegformerForImageClassification]]

```python
transformers.SegformerForImageClassification(config: SegformerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/modeling_segformer.py#L410)

**参数：**

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

SegFormer 模型，顶部带有图像分类头（在最终隐藏状态之上添加一个线性层），例如用于 ImageNet。

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

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/modeling_segformer.py#L423)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`，*可选*) : 与输入图像对应的张量。可以使用 [SegformerImageProcessor](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerImageProcessor) 获取像素值。有关详细信息，请参阅 [SegformerImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [SegformerImageProcessor](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerImageProcessor) 处理图像）。

labels (`torch.LongTensor`，形状为 `(batch_size,)`，*可选*) : 用于计算图像分类/回归损失的标签。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels == 1`，则计算回归损失（均方损失）；如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

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

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

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

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **logits**（形状为 `(batch_size, config.num_labels)` 的 `torch.Tensor`）-- 分类（或当 config.num_labels==1 时为回归）得分（SoftMax 之前）。
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个阶段输出的一个张量），形状为 `(batch_size, num_channels, height, width)`。模型在每个阶段输出处的隐藏状态（也称为特征图）。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, patch_size, sequence_length)`。

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

示例：

```python
>>> from transformers import AutoImageProcessor, SegformerForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("ByteDance-Seed/Seed-OSS-36B-Instruct")
>>> model = SegformerForImageClassification.from_pretrained("ByteDance-Seed/Seed-OSS-36B-Instruct")

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

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

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...
```

## SegformerForSemanticSegmentation[[transformers.SegformerForSemanticSegmentation]]

#### transformers.SegformerForSemanticSegmentation[[transformers.SegformerForSemanticSegmentation]]

```python
transformers.SegformerForSemanticSegmentation(config: SegformerConfig)
```

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/modeling_segformer.py#L534)

**参数：**

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

SegFormer 模型，在顶部采用全 MLP 解码头，例如用于 ADE20k、CityScapes。

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

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

[来源](https://github.com/huggingface/transformers/blob/main/src/transformers/models/segformer/modeling_segformer.py#L543)

**参数：**

pixel_values (`torch.Tensor`，形状为 `(batch_size, num_channels, image_size, image_size)`)：与输入图像对应的张量。可以使用 [SegformerImageProcessor](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerImageProcessor) 获取像素值。有关详细信息，请参阅 [SegformerImageProcessor.__call__()](/docs/transformers/main/zh/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)（`processor_class` 使用 [SegformerImageProcessor](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerImageProcessor) 处理图像）。

labels (`torch.LongTensor`，形状为 `(batch_size, height, width)`，*可选*) : 用于计算损失的真实语义分割图。索引应在 `[0, ..., config.num_labels - 1]` 范围内。如果 `config.num_labels > 1`，则计算分类损失（交叉熵）。

**返回：** [SemanticSegmenterOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 或 `tuple(torch.Tensor)`

一个 [SemanticSegmenterOutput](/docs/transformers/main/zh/main_classes/output#transformers.modeling_outputs.SemanticSegmenterOutput) 或 `torch.Tensor` 元组（如果传入了 `return_dict=False` 或 `config.return_dict=False`），其包含的元素取决于配置（[SegformerConfig](/docs/transformers/main/zh/model_doc/segformer#transformers.SegformerConfig)）和输入。

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

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

- **loss** (`torch.Tensor`，形状为 `(1,)`，*可选*，当提供 `labels` 时返回) -- 分类损失（如果 config.num_labels==1，则为回归损失）。
- **logits**（形状为 `(batch_size, config.num_labels, logits_height, logits_width)` 的 `torch.Tensor`）-- 每个像素的分类分数。

  

  返回的 logits 大小不一定与作为输入传入的 `pixel_values` 相同。这样设计是为了避免进行两次插值，从而在用户需要将 logits 调整为原始图像尺寸作为后处理时损失部分质量。您应始终检查 logits 的形状，并根据需要进行调整。

  
- **hidden_states** (`tuple(torch.Tensor)`，*可选*，在传入 `output_hidden_states=True` 或 `config.output_hidden_states=True` 时返回) -- 一个 `torch.Tensor` 元组（如果模型具有嵌入层，则包含嵌入层输出的一个张量，以及每个层输出的一个张量），形状为 `(batch_size, patch_size, hidden_size)`。

  模型在每一层输出处的隐藏状态，以及可选的初始嵌入输出。
- **attentions** (`tuple(torch.Tensor)`，*可选*，当传入 `output_attentions=True` 或 `config.output_attentions=True` 时返回) -- 一个 `torch.Tensor` 元组（每层一个），形状为 `(batch_size, num_heads, patch_size, sequence_length)`。

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

示例：

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

>>> image_processor = AutoImageProcessor.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")
>>> model = SegformerForSemanticSegmentation.from_pretrained("nvidia/segformer-b0-finetuned-ade-512-512")

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

>>> inputs = image_processor(images=image, return_tensors="pt")
>>> outputs = model(**inputs)
>>> logits = outputs.logits  # shape (batch_size, num_labels, height/4, width/4)
>>> list(logits.shape)
[1, 150, 128, 128]
```

