Transformers 文档
图像处理器实用程序
并获得增强的文档体验
开始使用
图像处理器实用程序
本页列出了图像处理器使用的所有实用函数,主要是用于处理图像的功能转换。
这些功能大多只在您研究库中图像处理器的代码时有用。
图像转换
transformers.image_transforms.center_crop
< 源 >( 图像: ndarray 尺寸: 元组 数据格式: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None 输入数据格式: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None ) → np.ndarray
参数
- 图像 (
np.ndarray
) — 要裁剪的图像。 - 尺寸 (
tuple[int, int]
) — 裁剪图像的目标尺寸。 - 数据格式 (
str
或ChannelDimension
, 可选) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。如果未设置,将使用输入图像的推断格式。
- 输入数据格式 (
str
或ChannelDimension
, 可选) — 输入图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。如果未设置,将使用输入图像的推断格式。
返回
np.ndarray
裁剪后的图像。
使用中心裁剪将 image
裁剪到指定的 size
。请注意,如果图像太小而无法裁剪到给定尺寸,它将被填充(因此返回结果始终是 size
尺寸)。
将边界框从中心格式转换为角点格式。
中心格式:包含框中心坐标及其宽度、高度尺寸(center_x、center_y、width、height)角点格式:包含框左上角和右下角的坐标(top_left_x、top_left_y、bottom_right_x、bottom_right_y)
将边界框从角点格式转换为中心格式。
角点格式:包含框的左上角和右下角坐标(top_left_x, top_left_y, bottom_right_x, bottom_right_y)中心格式:包含框中心坐标及其宽度、高度尺寸(center_x, center_y, width, height)
将唯一 ID 转换为 RGB 颜色。
transformers.image_transforms.normalize
< 源 >( 图像: ndarray 平均值: typing.Union[float, collections.abc.Collection[float]] 标准差: typing.Union[float, collections.abc.Collection[float]] 数据格式: typing.Optional[transformers.image_utils.ChannelDimension] = None 输入数据格式: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None )
使用 mean
和 std
指定的平均值和标准差对 image
进行归一化。
图像 = (图像 - 平均值) / 标准差
transformers.image_transforms.pad
< 源 >( 图像: ndarray 填充: typing.Union[int, tuple[int, int], collections.abc.Iterable[tuple[int, int]]] 模式: PaddingMode = <PaddingMode.CONSTANT: 'constant'> 常量值: typing.Union[float, collections.abc.Iterable[float]] = 0.0 数据格式: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None 输入数据格式: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None ) → np.ndarray
参数
- 图像 (
np.ndarray
) — 要填充的图像。 - 填充 (
int
或tuple[int, int]
或Iterable[tuple[int, int]]
) — 应用于高度、宽度轴边缘的填充。可以是以下三种格式之一:((before_height, after_height), (before_width, after_width))
每个轴的唯一填充宽度。((before, after),)
高度和宽度具有相同的填充宽度。(pad,)
或 int 是所有轴的 before = after = pad 宽度的快捷方式。
- 模式 (
PaddingMode
) — 要使用的填充模式。可以是以下之一:"constant"
: 用常量值填充。"reflect"
: 沿每个轴用向量在向量的第一个和最后一个值上的反射填充。"replicate"
: 沿每个轴用数组边缘的最后一个值的复制填充。"symmetric"
: 沿数组边缘用向量的反射填充。
- 常量值 (
float
或Iterable[float]
, 可选) — 如果mode
为"constant"
,则用于填充的值。 - 数据格式 (
str
或ChannelDimension
, 可选) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。如果未设置,将与输入图像的格式相同。
- 输入数据格式 (
str
或ChannelDimension
, 可选) — 输入图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。如果未设置,将使用输入图像的推断格式。
返回
np.ndarray
填充后的图像。
使用指定的 (height, width) padding
和 mode
对 image
进行填充。
将 RGB 颜色转换为唯一 ID。
transformers.image_transforms.rescale
< 源 >( 图像: ndarray 比例: float 数据格式: typing.Optional[transformers.image_utils.ChannelDimension] = None dtype: dtype = <class 'numpy.float32'> 输入数据格式: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None ) → np.ndarray
通过 scale
重新缩放 image
。
transformers.image_transforms.resize
< 源 >( 图像: ndarray 尺寸: 元组 重采样: PILImageResampling = None 缩减间隙: typing.Optional[int] = None 数据格式: typing.Optional[transformers.image_utils.ChannelDimension] = None 返回numpy: bool = True 输入数据格式: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None ) → np.ndarray
参数
- 图像 (
np.ndarray
) — 要调整大小的图像。 - 尺寸 (
tuple[int, int]
) — 用于调整图像大小的尺寸。 - 重采样 (
int
, 可选, 默认为PILImageResampling.BILINEAR
) — 用户重采样的过滤器。 - 缩减间隙 (
int
, 可选) — 通过两步调整图像大小来应用优化。reducing_gap
越大,结果越接近公平重采样。有关更多详细信息,请参阅相应的 Pillow 文档。 - 数据格式 (
ChannelDimension
, 可选) — 输出图像的通道维度格式。如果未设置,将使用输入推断的格式。 - 返回numpy (
bool
, 可选, 默认为True
) — 是否将调整大小后的图像作为 numpy 数组返回。如果为 False,则返回PIL.Image.Image
对象。 - 输入数据格式 (
ChannelDimension
, 可选) — 输入图像的通道维度格式。如果未设置,将使用输入推断的格式。
返回
np.ndarray
调整大小后的图像。
使用 PIL 库将 image
调整为 size
指定的 (height, width)
。
transformers.image_transforms.to_pil_image
< 源 >( 图像: typing.Union[numpy.ndarray, ForwardRef('PIL.Image.Image'), ForwardRef('torch.Tensor'), ForwardRef('tf.Tensor'), ForwardRef('jnp.ndarray')] do_rescale: typing.Optional[bool] = None 图像模式: typing.Optional[str] = None 输入数据格式: typing.Union[transformers.image_utils.ChannelDimension, str, NoneType] = None ) → PIL.Image.Image
参数
- 图像 (
PIL.Image.Image
或numpy.ndarray
或torch.Tensor
或tf.Tensor
) — 要转换为PIL.Image
格式的图像。 - do_rescale (
bool
, 可选) — 是否应用缩放因子(使像素值在 0 到 255 之间)。如果图像类型是浮点类型且转换为int
会导致精度损失,则默认为True
,否则为False
。 - 图像模式 (
str
, 可选) — 用于 PIL 图像的模式。如果未设置,将使用输入图像类型的默认模式。 - 输入数据格式 (
ChannelDimension
, 可选) — 输入图像的通道维度格式。如果未设置,将使用输入推断的格式。
返回
PIL.Image.Image
转换后的图像。
将 image
转换为 PIL 图像。根据需要可选地重新缩放并重新放置通道维度作为最后一个轴。
ImageProcessingMixin
这是一个图像处理器 mixin,用于为顺序和图像特征提取器提供保存/加载功能。
将单个或URL列表转换为相应的 PIL.Image
对象。
如果传入单个URL,则返回值为单个对象。如果传入列表,则返回对象列表。
from_dict
< 源 >( image_processor_dict: dict **kwargs ) → ImageProcessingMixin
参数
- image_processor_dict (
dict[str, Any]
) — 用于实例化图像处理器对象的字典。可以通过使用 to_dict() 方法从预训练检查点检索此类字典。 - kwargs (
dict[str, Any]
) — 用于初始化图像处理器对象的附加参数。
从这些参数实例化的图像处理器对象。
从 Python 参数字典实例化 ImageProcessingMixin 类型。
from_json_file
< 源 >( json_file: typing.Union[str, os.PathLike] ) → ImageProcessingMixin 类型的图像处理器
从 JSON 参数文件路径实例化 ImageProcessingMixin 类型的图像处理器。
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 持有者授权令牌。如果为True
或未指定,将使用运行huggingface-cli login
时生成的令牌(存储在~/.huggingface
中)。 - revision (
str
, 可选, 默认为"main"
) — 要使用的特定模型版本。它可以是分支名称、标签名称或提交 ID,因为我们使用基于 Git 的系统在 huggingface.co 上存储模型和其他工件,因此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}
get_image_processor_dict
< 源 >( pretrained_model_name_or_path: typing.Union[str, os.PathLike] **kwargs ) → tuple[Dict, Dict]
从 `pretrained_model_name_or_path` 解析为参数字典,用于使用 `from_dict` 实例化 `~image_processor_utils.ImageProcessingMixin` 类型的图像处理器。
push_to_hub
< 源 >( repo_id: str use_temp_dir: typing.Optional[bool] = None commit_message: typing.Optional[str] = None private: typing.Optional[bool] = None token: typing.Union[bool, str, NoneType] = None max_shard_size: typing.Union[str, int, NoneType] = '5GB' create_pr: bool = False safe_serialization: bool = True revision: typing.Optional[str] = None commit_description: typing.Optional[str] = None tags: typing.Optional[list[str]] = None **deprecated_kwargs )
参数
- repo_id (
str
) — 您要将图像处理器推送到的仓库名称。当推送到给定组织时,它应包含您的组织名称。 - use_temp_dir (
bool
, 可选) — 是否使用临时目录来存储在推送到 Hub 之前保存的文件。如果没有名为repo_id
的目录,则默认为True
,否则为False
。 - commit_message (
str
, 可选) — 推送时的提交消息。默认为"Upload image processor"
。 - private (
bool
, 可选) — 是否将仓库设为私有。如果为None
(默认),则仓库将是公开的,除非组织的默认设置是私有。如果仓库已存在,则此值将被忽略。 - token (
bool
或str
, 可选) — 用于远程文件的 HTTP 持有者授权令牌。如果为True
,将使用运行huggingface-cli login
时生成的令牌(存储在~/.huggingface
中)。如果未指定repo_url
,则默认为True
。 - max_shard_size (
int
或str
, 可选, 默认为"5GB"
) — 仅适用于模型。检查点分片前的最大大小。检查点分片的大小将低于此大小。如果表示为字符串,则需要是数字后跟单位(如"5MB"
)。我们默认将其设为"5GB"
,以便用户可以在免费的 Google Colab 实例上轻松加载模型,而不会出现任何 CPU OOM 问题。 - create_pr (
bool
, 可选, 默认为False
) — 是否为上传的文件创建 PR 或直接提交。 - safe_serialization (
bool
, 可选, 默认为True
) — 是否将模型权重转换为 safetensors 格式以进行更安全的序列化。 - revision (
str
, 可选) — 要将上传文件推送到的分支。 - commit_description (
str
, 可选) — 将创建的提交的描述 - tags (
list[str]
, 可选) — 要推送到 Hub 的标签列表。
将图像处理器文件上传到 🤗 模型中心。
示例
from transformers import AutoImageProcessor
image processor = AutoImageProcessor.from_pretrained("google-bert/bert-base-cased")
# Push the image processor to your namespace with the name "my-finetuned-bert".
image processor.push_to_hub("my-finetuned-bert")
# Push the image processor to an organization with the name "my-finetuned-bert".
image processor.push_to_hub("huggingface/my-finetuned-bert")
register_for_auto_class
< 源 >( auto_class = 'AutoImageProcessor' )
将此类别注册到给定的自动类别。这仅应用于自定义图像处理器,因为库中的图像处理器已映射到 `AutoImageProcessor`。
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()` 类方法重新加载它。
将此实例序列化为 Python 字典。
to_json_file
< 源 >( json_file_path: typing.Union[str, os.PathLike] )
将此实例保存到 JSON 文件。
将此实例序列化为 JSON 字符串。