Transformers documentation

图像处理器

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.24.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

图像处理器

图像处理器负责加载图像(可选)、为视觉模型准备输入特征以及对其输出进行后处理。这包括调整大小、归一化以及转换为 PyTorch 和 Numpy 张量等变换。它还可能包括特定于模型的后处理,例如将 logits 转换为分割掩码。

图像处理器采用基于后端的架构。类层次结构如下:

  • BaseImageProcessor — 抽象基类(仅为向后兼容而保留;请勿直接实例化)
    • TorchvisionBackend — 默认的 torchvision 支持后端。具有 GPU 加速,速度显著快于 PIL 后端。所有模型都暴露一个继承自该后端的 <Model>ImageProcessor 类。
    • PilBackend — PIL/NumPy 替代后端。可移植,仅支持 CPU。仅通过 <Model>ImageProcessorPil 类为较旧的模型提供;当需要与原始实现保持精确的数值一致性时非常有用。

两种后端暴露了相同的 API。使用 backend 属性可以检查已加载的处理器使用的是哪种后端(例如 processor.backend == "torchvision")。

将 backend 传递给 AutoImageProcessor.from_pretrained() 以选择后端。当省略 backend(默认情况)时,如果已安装 torchvision,则选择 torchvision,否则使用 PIL。少数使用 Lanczos 插值的模型(Chameleon、Flava、Idefics3、SmolVLM)是例外,当 torchvision < 0.27 时,它们默认使用 PIL。对于 torchvision < 0.27 的这些模型,强制指定 backend="torchvision" 会回退到 BICUBIC 插值,因为 torchvision 仅从 0.27 版本开始才支持张量的 Lanczos 插值。

from transformers import AutoImageProcessor

# Default: picks torchvision if available, otherwise pil
processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50")

# Explicitly request torchvision
processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50", backend="torchvision")

# Explicitly request PIL
processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50", backend="pil")

使用 torchvision 后端时,可以设置 device 参数来指定执行处理的设备。默认情况下,如果输入是张量,处理将在与输入相同的设备上执行;否则,处理将在 CPU 上执行。

import torch
from torchvision.io import read_image
from transformers import DetrImageProcessor

device = torch.accelerator.current_accelerator().type if torch.accelerator.is_available() else "cpu"

images = read_image("image.jpg")
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
images_processed = processor(images, return_tensors="pt", device=device)

以下是 DETR 和 RT-DETR 模型中 torchvision 与 PIL 后端的运行速度对比,以及它们对整体推理时间的影响:

这些基准测试在 AWS EC2 g5.2xlarge 实例 上运行,使用了 NVIDIA A10G Tensor Core GPU。

ImageProcessingMixin

class transformers.ImageProcessingMixin

< >

( **kwargs )

这是一个图像处理器混入类,用于为顺序特征提取器和图像特征提取器提供保存/加载功能。

from_pretrained

< >

( pretrained_model_name_or_path: str | os.PathLikecache_dir: str | os.PathLike | None = Noneforce_download: bool = Falselocal_files_only: bool = Falsetoken: str | bool | None = Nonerevision: str = 'main'**kwargs )

参数

  • pretrained_model_name_or_path (str 或 os.PathLike) — 可以是以下之一:
    • 一个字符串,即托管在 huggingface.co 上某个模型仓库中的预训练 model id 的 image_processor。
    • 指向一个目录的路径,该目录包含使用 save_pretrained() 方法保存的图像处理器文件,例如 ./my_model_directory/。
    • 指向已保存的图像处理器 JSON 文件的路径,例如 ./my_model_directory/preprocessor_config.json。
  • cache_dir (str 或 os.PathLike,可选) — 如果不应使用标准缓存,则下载的预训练模型图像处理器应缓存到的目录路径。
  • force_download (bool,可选,默认为 False) — 是否强制(重新)下载图像处理器文件,并在缓存版本已存在时覆盖它们。
  • proxies (dict[str, str], 可选) — 按协议或端点使用的代理服务器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. 每次请求都会使用这些代理。
  • token (str 或 bool,可选) — 用于远程文件的 HTTP bearer 授权令牌。如果为 True 或未指定,则使用运行 hf auth login 时生成的令牌(存储在 ~/.huggingface 中)。
  • revision (str, 可选, 默认为 "main") — 要使用的特定模型版本。由于我们在 huggingface.co 上使用基于 git 的系统来存储模型和其他工件,因此它可以是分支名称、标签名称或提交 ID,所以 revision 可以是 git 允许的任何标识符。

    要测试您在 Hub 上创建的拉取请求,可以传入 revision="refs/pr/<pr_number>"。

  • return_unused_kwargs (bool,可选,默认为 False) — 如果为 False,则此函数仅返回最终的图像处理器对象。如果为 True,则此函数返回一个 Tuple(image_processor, unused_kwargs),其中 unused_kwargs 是一个字典,包含那些键不是图像处理器属性的键值对:即 kwargs 中未用于更新 image_processor 且被忽略的部分。
  • subfolder (str,可选,默认为 "") — 如果相关文件位于 huggingface.co 上模型仓库的子文件夹中,您可以在此处指定该文件夹的名称。
  • kwargs (dict[str, Any], 可选) — kwargs 中任何作为图像处理器属性的键的值,将用于覆盖已加载的值。对于键 不是 图像处理器属性的键值对,其行为由 return_unused_kwargs 关键字参数控制。

从图像处理器实例化 ImageProcessingMixin 的一种类型。

示例:

# We can't instantiate directly the base class *ImageProcessingMixin* so let's show the examples on a
# derived class: *CLIPImageProcessor*
image_processor = CLIPImageProcessor.from_pretrained(
    "openai/clip-vit-base-patch32"
)  # Download image_processing_config from huggingface.co and cache.
image_processor = CLIPImageProcessor.from_pretrained(
    "./test/saved_model/"
)  # E.g. image processor (or model) was saved using *save_pretrained('./test/saved_model/')*
image_processor = CLIPImageProcessor.from_pretrained("./test/saved_model/preprocessor_config.json")
image_processor = CLIPImageProcessor.from_pretrained(
    "openai/clip-vit-base-patch32", do_normalize=False, foo=False
)
assert image_processor.do_normalize is False
image_processor, unused_kwargs = CLIPImageProcessor.from_pretrained(
    "openai/clip-vit-base-patch32", do_normalize=False, foo=False, return_unused_kwargs=True
)
assert image_processor.do_normalize is False
assert unused_kwargs == {"foo": False}

save_pretrained

< >

( save_directory: str | os.PathLikepush_to_hub: bool = False**kwargs )

参数

  • save_directory (str 或 os.PathLike) — 用于保存图像处理器 JSON 文件的目录(如果该目录不存在,则会自动创建)。
  • push_to_hub (bool,可选,默认为 False) — 是否在保存模型后将其推送到 Hugging Face 模型库。您可以使用 repo_id 指定要推送到的仓库(默认使用您命名空间中 save_directory 的名称)。
  • kwargs (dict[str, Any],可选) — 传递给 push_to_hub() 方法的额外关键字参数。

将图像处理器对象保存到目录 save_directory,以便之后可以使用 from_pretrained() 类方法重新加载。

BatchFeature

class transformers.BatchFeature

< >

( data: dict[str, typing.Any] | None = Nonetensor_type: None | str | transformers.utils.generic.TensorType = Noneskip_tensor_conversion: list[str] | set[str] | None = None )

参数

  • data (dict, 可选) — 由 call/pad 方法返回的列表/数组/张量字典(例如 ‘input_values’、‘attention_mask’ 等)。
  • tensor_type (Union[None, str, TensorType],可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。
  • skip_tensor_conversion (list[str] 或 set[str],可选) — 不应转换为张量的键的列表或集合,即使指定了 tensor_type。

保存 pad() 和特征提取器特定的 __call__ 方法的输出。

此类派生自 Python 字典,可用作字典。

convert_to_tensors

< >

( tensor_type: str | transformers.utils.generic.TensorType | None = Noneskip_tensor_conversion: list[str] | set[str] | None = None )

参数

  • tensor_type (str 或 TensorType,可选) — 要使用的张量类型。如果为 str,则应为枚举 TensorType 的某个值。如果为 None,则不进行任何修改。
  • skip_tensor_conversion (list[str] 或 set[str],可选) — 不应转换为张量的键的列表或集合,即使指定了 tensor_type。

将内部内容转换为张量。

注意: 不具有数组结构(例如字符串、字典、字符串列表)的值会被自动跳过,不会转换为张量。对于不规则数组(长度不同的数组列表),系统仍会尝试进行转换,但在转换过程中可能会引发错误。

到

< >

( *args**kwargs ) → BatchFeature

参数

  • args (Tuple) — 将传递给张量的 to(...) 函数。
  • kwargs (Dict, 可选) — 将传递给张量的 to(...) 函数。 若要启用异步数据传输,请在 kwargs 中设置 non_blocking 标志(默认为 False)。

返回值

BatchFeature

修改后的同一实例。

通过调用 v.to(*args, **kwargs) 将所有值发送到设备(仅限 PyTorch)。这应支持转换为不同的 dtypes,并将 BatchFeature 发送到不同的 device。

BaseImageProcessor

class transformers.BaseImageProcessor

< >

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

基于继承式后端架构的图像处理器基类。

该类定义了预处理流程:kwargs 验证、输入准备,以及分发到后端的 _preprocess 方法。后端子类(TorchvisionBackend、PilBackend)继承自该类,并实现实际的图像操作(resize、crop、rescale、normalize 等)。特定于模型的图像处理器随后继承自相应的后端类。

架构概览

类层次结构如下:

BaseImageProcessor(此类) ├── TorchvisionBackend(GPU 加速,torch.Tensor) │ └── ModelImageProcessor(例如 LlavaNextImageProcessor) └── PilBackend(可移植 CPU,np.ndarray) └── ModelImageProcessorPil(例如 CLIPImageProcessorPil)

预处理流程如下:

call() → preprocess() → _preprocess_image_like_inputs() → _prepare_image_like_inputs() (对每张图像调用 process_image) → _preprocess() (批量操作:调整大小、裁剪等)

  • process_image:由后端实现。将单个原始输入(PIL、NumPy 或 Tensor)转换为后端的工作格式(torch.Tensor 或 np.ndarray),并处理 RGB 转换和通道重排。
  • _preprocess:由后端实现。执行实际的批处理操作(调整大小、中心裁剪、重新缩放、归一化、填充),并返回一个 BatchFeature。

基础实现

对于仅需标准操作(调整大小、中心裁剪、重新缩放、归一化)的处理器,请继承自某个后端并定义类属性:

from transformers.image_processing_backends import PilBackend

class MyImageProcessorPil(PilBackend): resample = PILImageResampling.BILINEAR image_mean = IMAGENET_DEFAULT_MEAN image_std = IMAGENET_DEFAULT_STD size = {“height”: 224, “width”: 224} do_resize = True do_rescale = True do_normalize = True

后端的 _preprocess 方法会自动处理标准流水线。

自定义处理

对于需要自定义逻辑(例如基于 patch 的处理、多种输入类型)的处理器,请在您的模型专用处理器中重写 _preprocess。_preprocess 方法接收已准备好的图像(已转换为后端格式,且通道在前),并执行实际的处理:

class MyImageProcessor(TorchvisionBackend): def _preprocess(self, images, do_resize, size, do_normalize, image_mean, image_std, **kwargs):

按形状对图像进行分组,以实现高效的批量操作

grouped_images, grouped_images_index = group_images_by_shape(images) processed_groups = {} for shape, stacked_images in grouped_images.items(): if do_resize: stacked_images = self.resize(stacked_images, size=size) if do_normalize: stacked_images = self.normalize(stacked_images, mean=image_mean, std=image_std) processed_groups[shape] = stacked_images processed_images = reorder_images(processed_groups, grouped_images_index) return BatchFeature(data={“pixel_values”: processed_images})

对于处理多种输入类型(例如,图像 + 分割图)的处理器,请重写 _preprocess_image_like_inputs:

def _preprocess_image_like_inputs( self, images: ImageInput, segmentation_maps: ImageInput | None = None, kwargs, ) -> BatchFeature: images = self._prepare_image_like_inputs(images,kwargs) batch_feature = self._preprocess(images, **kwargs)

if segmentation_maps is not None: maps = self._prepare_image_like_inputs(segmentation_maps, kwargs) batch_feature[“labels”] = self._preprocess(maps,kwargs).pixel_values

return batch_feature

扩展后端行为

要为特定后端自定义操作,请继承该后端并重写其方法:

from transformers.image_processing_backends import TorchvisionBackend, PilBackend

class MyTorchvisionProcessor(TorchvisionBackend): def resize(self, image, size, **kwargs):

torchvision 的自定义调整大小逻辑

return super().resize(image, size, **kwargs)

class MyPilProcessor(PilBackend): def resize(self, image, size, **kwargs):

PIL 的自定义调整大小逻辑

return super().resize(image, size, **kwargs)

自定义参数

若要添加 ImagesKwargs 之外的参数,请创建一个自定义的 kwargs 类并将其设置为 valid_kwargs:

class MyImageProcessorKwargs(ImagesKwargs): custom_param: int | None = None

class MyImageProcessor(TorchvisionBackend): valid_kwargs = MyImageProcessorKwargs custom_param = 10 # 默认值

关键说明

  • 后端选择在类级别进行:继承自 TorchvisionBackend 或 PilBackend
  • 后端以 torch.Tensor(Torchvision)或 np.ndarray(PIL)的形式接收图像,且始终采用通道优先(channels-first)的格式
  • 在处理过程中,所有图像的通道维度都位于最前面,与后端无关
  • 用户未提供的参数将默认使用类属性值
  • Backend 类封装了与后端相关的逻辑(例如 resize、normalize 等),并且可以被重写

center_crop

< >

( image: ndarraysize: dict[str, int]data_format: str | transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None**kwargs )

参数

  • image (np.ndarray) — 要中心裁剪的图像。
  • size (dict[str, int]) — 输出图像的尺寸。
  • data_format (str 或 ChannelDimension, 可选) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
  • input_data_format (ChannelDimension 或 str, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。

将图像中心裁剪为 (size["height"], size["width"])。如果输入尺寸在任意边缘上小于 crop_size,则先用 0 填充图像,然后再进行中心裁剪。

normalize

< >

( image: ndarraymean: float | collections.abc.Iterable[float]std: float | collections.abc.Iterable[float]data_format: str | transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None**kwargs ) → np.ndarray

参数

  • image (np.ndarray) — 要归一化的图像。
  • mean (float 或 Iterable[float]) — 用于归一化的图像均值。
  • std (float 或 Iterable[float]) — 用于归一化的图像标准差。
  • data_format (str 或 ChannelDimension, 可选) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
  • input_data_format (ChannelDimension 或 str, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。

返回值

np.ndarray

归一化后的图像。

对图像进行归一化。image = (image - image_mean) / image_std。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]*argsimage_like_kwargs: dict[str, typing.Any] | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> ) → ~image_processing_base.BatchFeature

参数

  • 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 为整数时,是否在调整大小时默认使用正方形图像。
  • 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 张量中的整数列表进行转换。

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

process_image

< >

( *args**kwargs )

将单张原始图像处理后转换为后端的工作格式。

由后端子类(TorchvisionBackend、PilBackend)实现。将原始输入(PIL Image、NumPy 数组或 torch Tensor)转换为后端的内部格式(Torchvision 使用 torch.Tensor,PIL 使用 np.ndarray),处理 RGB 转换并确保通道优先(channels-first)的排列顺序。

rescale

< >

( image: ndarrayscale: floatdata_format: str | transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None**kwargs ) → np.ndarray

参数

  • image (np.ndarray) — 要重新缩放的图像。
  • scale (float) — 用于对像素值进行重新缩放的缩放因子。
  • data_format (str 或 ChannelDimension, 可选) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。
  • input_data_format (ChannelDimension 或 str, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。

返回值

np.ndarray

重新缩放后的图像。

按缩放因子对图像进行重新缩放。image = image * scale。

TorchvisionBackend

class transformers.TorchvisionBackend

< >

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

用于 GPU 加速批量图像处理的 Torchvision 后端。

center_crop

< >

( image: torch.Tensorsize: SizeDict**kwargs )

使用 Torchvision 对图像进行中心裁剪。

convert_to_rgb

< >

( image: torch.Tensorinput_data_format: str | transformers.image_utils.ChannelDimension | None = None )

将图像转换为 RGB 格式。

fetch_images

< >

( image_url_or_urls: str | list[str] | list[list[str]] )

将单个 URL / 路径或 URL / 路径列表转换为 torch.Tensor 对象。

已经是有效图像对象(张量、NumPy 数组、PIL 图像)的内容将原样传递,因此预先加载图像的调用方不会受到影响。

normalize

< >

( image: torch.Tensormean: float | collections.abc.Iterable[float]std: float | collections.abc.Iterable[float]inplace: bool = False**kwargs )

使用 Torchvision 对图像进行归一化。

填充

< >

( images: list['torch.Tensor']pad_size: SizeDict = Nonefill_value: int | None = 0padding_mode: str | None = 'constant'return_mask: bool = Falsedisable_grouping: bool | None = Falseis_nested: bool | None = False**kwargs )

使用 Torchvision 以批量操作的方式填充图像。

process_image

< >

( image: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]do_convert_rgb: bool | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = Nonedevice: typing.Optional[ForwardRef('torch.device')] = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )

使用 torchvision 后端处理单张图像。

rescale

< >

( image: torch.Tensorscale: float**kwargs )

使用 Torchvision 按缩放因子对图像进行缩放。

rescale_and_normalize

< >

( images: torch.Tensordo_rescale: boolrescale_factor: floatdo_normalize: boolimage_mean: float | list[float]image_std: float | list[float] )

使用 Torchvision 对图像进行缩放和归一化(为提升效率而融合)。

调整大小

< >

( image: torch.Tensorsize: SizeDictresample: PILImageResampling | tvF.InterpolationMode | int | None = Noneantialias: bool = True**kwargs )

使用 Torchvision 调整图像大小。

PilBackend

class transformers.PilBackend

< >

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

用于便携式纯 CPU 图像处理的 PIL/NumPy 后端。

center_crop

< >

( image: ndarraysize: SizeDict**kwargs )

使用 NumPy 对图像进行中心裁剪。

convert_to_rgb

< >

( image: ndarrayinput_data_format: str | transformers.image_utils.ChannelDimension | None = None )

将图像转换为 RGB 格式。

normalize

< >

( image: ndarraymean: float | collections.abc.Iterable[float]std: float | collections.abc.Iterable[float]**kwargs )

使用 NumPy 对图像进行归一化。

填充

< >

( images: list[numpy.ndarray]pad_size: SizeDict = Nonefill_value: int | None = 0padding_mode: str | None = 'constant'return_mask: bool = False**kwargs )

使用 NumPy 将图像填充到指定大小。

process_image

< >

( image: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]do_convert_rgb: bool | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'> )

使用 PIL 后端处理单张图像。

rescale

< >

( image: ndarrayscale: float**kwargs )

使用 NumPy 按缩放因子对图像进行缩放。

调整大小

< >

( image: ndarraysize: SizeDictresample: PILImageResampling | None = Nonereducing_gap: int | None = None**kwargs )

使用 PIL/NumPy 调整图像大小。

Update on GitHub