Transformers 文档
图像处理器
并获得增强的文档体验
开始使用
图像处理器
图像处理器负责为视觉模型准备输入特征,并对其输出进行后处理。这包括调整大小、归一化以及转换为 PyTorch、TensorFlow、Flax 和 Numpy 张量等变换。它也可能包括特定模型的后处理,例如将 logits 转换为分割掩码。
少数模型已提供快速图像处理器,未来将会有更多模型支持。它们基于 torchvision 库,能显著提升速度,尤其是在 GPU 上处理时。它们与基本图像处理器具有相同的 API,可作为直接替代品使用。要使用快速图像处理器,你需要安装 `torchvision` 库,并在实例化图像处理器时将 `use_fast` 参数设置为 `True`。
from transformers import AutoImageProcessor
processor = AutoImageProcessor.from_pretrained("facebook/detr-resnet-50", use_fast=True)
请注意,`use_fast` 将在未来的版本中默认设置为 `True`。
使用快速图像处理器时,你还可以设置 `device` 参数来指定处理应在哪个设备上进行。默认情况下,如果输入是张量,则处理在与输入相同的设备上进行;否则在 CPU 上进行。
from torchvision.io import read_image
from transformers import DetrImageProcessorFast
images = read_image("image.jpg")
processor = DetrImageProcessorFast.from_pretrained("facebook/detr-resnet-50")
images_processed = processor(images, return_tensors="pt", device="cuda")
以下是 `DETR` 和 `RT-DETR` 模型的基准和快速图像处理器的速度比较,以及它们对整体推理时间的影响:




这些基准测试在 AWS EC2 g5.2xlarge 实例 上运行,使用 NVIDIA A10G Tensor Core GPU。
ImageProcessingMixin
这是一个图像处理器混合类(mixin),用于为序列和图像特征提取器提供保存/加载功能。
from_pretrained
< 源 >( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[str, bool, NoneType] = None revision: str = 'main' **kwargs )
参数
- pretrained_model_name_or_path (
str
或os.PathLike
) — 这可以是以下之一:- 一个字符串,即托管在 huggingface.co 的模型仓库中的预训练 image_processor 的 *模型 ID*。
- 一个包含使用 save_pretrained() 方法保存的图像处理器文件的*目录*路径,例如:`./my_model_directory/`。
- 一个指向已保存的图像处理器 JSON *文件*的路径或 URL,例如:`./my_model_directory/preprocessor_config.json`。
- cache_dir (
str
或os.PathLike
, *可选*) — 如果不使用标准缓存,则为下载的预训练模型图像处理器应缓存到的目录路径。 - force_download (
bool
, *可选*, 默认为False
) — 是否强制(重新)下载图像处理器文件并覆盖已存在的缓存版本。 - resume_download — 已弃用并忽略。所有下载现在都默认在可能的情况下断点续传。将在 Transformers 的 v5 版本中移除。
- proxies (
dict[str, str]
, *可选*) — 一个按协议或端点使用的代理服务器字典,例如,`{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}`。代理将在每个请求中使用。 - token (
str
或bool
, *可选*) — 用于远程文件的 HTTP Bearer 授权的令牌。如果为 `True` 或未指定,将使用运行 `huggingface-cli login` 时生成的令牌(存储在 `~/.huggingface` 中)。 - revision (
str
, *可选*, 默认为"main"
) — 要使用的特定模型版本。它可以是分支名、标签名或提交 ID,因为我们在 huggingface.co 上使用基于 Git 的系统来存储模型和其他工件,所以 `revision` 可以是 Git 允许的任何标识符。
从图像处理器实例化一个 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: typing.Union[str, os.PathLike] push_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: typing.Optional[dict[str, typing.Any]] = None tensor_type: typing.Union[NoneType, str, transformers.utils.generic.TensorType] = None )
保存 pad() 方法和特征提取器特定的 `__call__` 方法的输出。
该类派生自 Python 字典,可以像字典一样使用。
convert_to_tensors
< 源 >( tensor_type: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None )
参数
- tensor_type (
str
或 TensorType, *可选*) — 要使用的张量类型。如果为 `str`,则应为枚举 TensorType 的值之一。如果为 `None`,则不进行修改。
将内部内容转换为张量。
到
< 源 >( *args **kwargs ) → BatchFeature
通过调用 `v.to(*args, **kwargs)` 将所有值发送到指定设备(仅限 PyTorch)。这应该支持转换为不同的 `dtypes` 并将 `BatchFeature` 发送到不同的 `device`。
BaseImageProcessor
center_crop
< 源 >( image: ndarray size: dict data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )
参数
- image (
np.ndarray
) — 要进行中心裁剪的图像。 - size (
dict[str, int]
) — 输出图像的大小。 - data_format (
str
或ChannelDimension
, *可选*) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:- `"channels_first"` 或 `ChannelDimension.FIRST`:图像格式为 (通道数, 高度, 宽度)。
- `"channels_last"` 或 `ChannelDimension.LAST`:图像格式为 (高度, 宽度, 通道数)。
- input_data_format (
ChannelDimension
或str
, *可选*) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:- `"channels_first"` 或 `ChannelDimension.FIRST`:图像格式为 (通道数, 高度, 宽度)。
- `"channels_last"` 或 `ChannelDimension.LAST`:图像格式为 (高度, 宽度, 通道数)。
将图像中心裁剪为 `(size["height"], size["width"])`。如果输入尺寸在任何一边小于 `crop_size`,则图像将用 0 填充,然后进行中心裁剪。
归一化
< 源 >( image: ndarray mean: typing.Union[float, collections.abc.Iterable[float]] std: typing.Union[float, collections.abc.Iterable[float]] data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs ) → np.ndarray
参数
- image (
np.ndarray
) — 要归一化的图像。 - mean (
float
或Iterable[float]
) — 用于归一化的图像均值。 - std (
float
或Iterable[float]
) — 用于归一化的图像标准差。 - data_format (
str
或ChannelDimension
, *可选*) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:- `"channels_first"` 或 `ChannelDimension.FIRST`:图像格式为 (通道数, 高度, 宽度)。
- `"channels_last"` 或 `ChannelDimension.LAST`:图像格式为 (高度, 宽度, 通道数)。
- input_data_format (
ChannelDimension
或str
, *可选*) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:- `"channels_first"` 或 `ChannelDimension.FIRST`:图像格式为 (通道数, 高度, 宽度)。
- `"channels_last"` 或 `ChannelDimension.LAST`:图像格式为 (高度, 宽度, 通道数)。
返回
np.ndarray
归一化后的图像。
归一化图像。`image = (image - image_mean) / image_std`。
rescale
< 源 >( image: ndarray scale: float data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs ) → np.ndarray
参数
- image (
np.ndarray
) — 要重新缩放的图像。 - scale (
float
) — 用于重新缩放像素值的缩放因子。 - data_format (
str
或ChannelDimension
, *可选*) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:- `"channels_first"` 或 `ChannelDimension.FIRST`:图像格式为 (通道数, 高度, 宽度)。
- `"channels_last"` 或 `ChannelDimension.LAST`:图像格式为 (高度, 宽度, 通道数)。
- input_data_format (
ChannelDimension
或str
, *可选*) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:- `"channels_first"` 或 `ChannelDimension.FIRST`:图像格式为 (通道数, 高度, 宽度)。
- `"channels_last"` 或 `ChannelDimension.LAST`:图像格式为 (高度, 宽度, 通道数)。
返回
np.ndarray
重新缩放后的图像。
通过一个缩放因子重新缩放图像。`image = image * scale`。
BaseImageProcessorFast
class transformers.BaseImageProcessorFast
< source >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
center_crop
< source >( image: torch.Tensor size: dict **kwargs ) → torch.Tensor
将图像中心裁剪为 `(size["height"], size["width"])`。如果输入尺寸在任何一边小于 `crop_size`,则图像将用 0 填充,然后进行中心裁剪。
compile_friendly_resize
< source >( image: torch.Tensor new_size: tuple interpolation: typing.Optional[ForwardRef('F.InterpolationMode')] = None antialias: bool = True )
F.resize
的包装器,使其在图像为 uint8 张量时与 torch.compile 兼容。
转换为 RGB
< source >( image: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] ) → ImageInput
将图像转换为 RGB 格式。仅当图像类型为 PIL.Image.Image 时才进行转换,否则按原样返回图像。
从 kwargs 字典中过滤掉未使用的关键字参数。
归一化
< source >( image: torch.Tensor mean: typing.Union[float, collections.abc.Iterable[float]] std: typing.Union[float, collections.abc.Iterable[float]] **kwargs ) → torch.Tensor
归一化图像。`image = (image - image_mean) / image_std`。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) → <class 'transformers.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
。 - do_resize (
bool
, optional) — 是否调整图像大小。 - size (
dict[str, int]
, optional) — 描述模型的最大输入尺寸。 - default_to_square (
bool
, optional) — 如果 `size` 是一个整数,在调整大小时是否默认为方形图像。 - resample (
Union[PILImageResampling, F.InterpolationMode, NoneType]
) — 调整图像大小时使用的重采样滤波器。可以是 `PILImageResampling` 枚举之一。仅在 `do_resize` 设置为 `True` 时有效。 - do_center_crop (
bool
, optional) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, optional) — 应用 `center_crop` 后输出图像的尺寸。 - do_rescale (
bool
, optional) — 是否重新缩放图像。 - rescale_factor (
Union[int, float, NoneType]
) — 如果 `do_rescale` 设置为 `True`,用于重新缩放图像的缩放因子。 - do_normalize (
bool
, optional) — 是否对图像进行归一化。 - image_mean (
Union[float, list[float], NoneType]
) — 用于归一化的图像均值。仅在 `do_normalize` 设置为 `True` 时有效。 - image_std (
Union[float, list[float], NoneType]
) — 用于归一化的图像标准差。仅在 `do_normalize` 设置为 `True` 时有效。 - do_convert_rgb (
bool
, optional) — 是否将图像转换为 RGB 格式。 - return_tensors (
Union[str, ~utils.generic.TensorType, NoneType]
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
~image_utils.ChannelDimension
, optional) — 仅支持 `ChannelDimension.FIRST`。为与慢速处理器兼容而添加。 - input_data_format (
Union[str, ~image_utils.ChannelDimension, NoneType]
) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
- device (
torch.device
, optional) — 处理图像的设备。如果未设置,则从输入图像中推断设备。 - disable_grouping (
bool
, optional) — 是否禁用按尺寸对图像进行分组,以便单独处理而非批量处理。如果为 None,则在图像位于 CPU 上时设置为 True,否则为 False。此选择基于经验观察,详见:https://github.com/huggingface/transformers/pull/38157
返回
<class 'transformers.image_processing_base.BatchFeature'>
- data (
dict
) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。 - tensor_type (
Union[None, str, TensorType]
, 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。
rescale
< source >( image: torch.Tensor scale: float **kwargs ) → torch.Tensor
通过一个缩放因子重新缩放图像。`image = image * scale`。
rescale_and_normalize
< source >( images: torch.Tensor do_rescale: bool rescale_factor: float do_normalize: bool image_mean: typing.Union[float, list[float]] image_std: typing.Union[float, list[float]] )
重新缩放和归一化图像。
resize
< source >( image: torch.Tensor size: SizeDict interpolation: F.InterpolationMode = None antialias: bool = True **kwargs ) → torch.Tensor
将图像调整为 (size["height"], size["width"])
。