Transformers documentation

图像处理器实用工具

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

图像处理器实用工具

本页列出了图像处理器所使用的全部实用函数,主要是用于处理图像的函数式变换。

其中大部分内容仅在你研究该库中图像处理器代码时才有用。

图像变换

transformers.image_transforms.center_crop

< >

( image: ndarraysize: tuple[int, int]data_format: str | transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → np.ndarray

参数

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

返回值

np.ndarray

裁剪后的图像。

使用中心裁剪将 image 裁剪为指定的 size。请注意,如果图像尺寸过小,无法裁剪到给定大小,则会进行填充(因此返回的结果始终为 size 大小)。

transformers.image_transforms.center_to_corners_format

< >

( bboxes_center: TensorType )

将边界框从中心格式转换为角点格式。

center 格式:包含框的中心点坐标及其宽度、高度尺寸 (center_x, center_y, width, height) corners 格式:包含框的左上角和右下角坐标 (top_left_x, top_left_y, bottom_right_x, bottom_right_y)

transformers.image_transforms.corners_to_center_format

< >

( bboxes_corners: TensorType )

将边界框从角点格式转换为中心格式。

corners 格式:包含框的左上角和右下角坐标 (top_left_x, top_left_y, bottom_right_x, bottom_right_y) center 格式:包含框的中心点坐标及其宽度、高度尺寸 (center_x, center_y, width, height)

transformers.image_transforms.id_to_rgb

< >

( id_map )

将唯一 ID 转换为 RGB 颜色。

transformers.image_transforms.normalize

< >

( image: ndarraymean: float | collections.abc.Collection[float]std: float | collections.abc.Collection[float]data_format: transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None )

参数

  • image (np.ndarray) — 要归一化的图像。
  • mean (float 或 Collection[float]) — 用于归一化的均值。
  • std (float 或 Collection[float]) — 用于归一化的标准差。
  • data_format (ChannelDimension,可选) — 输出图像的通道维度格式。如果未设置,将使用从输入推断出的格式。
  • input_data_format (ChannelDimension,可选) — 输入图像的通道维度格式。如果未设置,将使用从输入中推断出的格式。

使用 mean 和 std 指定的均值和标准差对 image 进行归一化。

image = (image - mean) / std

transformers.image_transforms.pad

< >

( image: ndarraypadding: int | tuple[int, int] | collections.abc.Iterable[tuple[int, int]]mode: PaddingMode = <PaddingMode.CONSTANT: 'constant'>constant_values: float | collections.abc.Iterable[float] = 0.0data_format: str | transformers.image_utils.ChannelDimension | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → np.ndarray

参数

  • image (np.ndarray) — 要填充的图像。
  • padding (int 或 tuple[int, int] 或 Iterable[tuple[int, int]]) — 应用于高度和宽度轴边缘的填充。可以是以下三种格式之一:
    • ((before_height, after_height), (before_width, after_width)) 每个轴上唯一的填充宽度。
    • ((before, after),) 表示高度和宽度使用相同的 before 和 after 填充。
    • (pad,) 或 int 是 before = after = pad 的简写,表示在所有轴上使用该宽度。
  • mode (PaddingMode) — 要使用的填充模式。可以是以下之一:
    • "constant":使用固定值进行填充。
    • "reflect":沿每个轴,使用向量首尾值处的镜像反射进行填充。
    • "replicate":沿每个轴,使用数组边缘最后一个值的复制进行填充。
    • "symmetric":通过沿数组边缘镜像反射向量进行填充。
  • constant_values (float 或 Iterable[float],可选) — 当 mode 为 "constant" 时,用于填充的值。
  • data_format (str 或 ChannelDimension, 可选) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first" 或 ChannelDimension.FIRST:图像采用 (num_channels, height, width) 格式。
    • "channels_last" 或 ChannelDimension.LAST:图像采用 (height, width, num_channels) 格式。 如果未设置,则与输入图像保持一致。
  • input_data_format (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 进行填充。

transformers.image_transforms.rgb_to_id

< >

( color )

将 RGB 颜色转换为唯一 ID。

transformers.image_transforms.rescale

< >

( image: ndarrayscale: floatdata_format: transformers.image_utils.ChannelDimension | None = Nonedtype: dtype = <class 'numpy.float32'>input_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → np.ndarray

参数

  • image (np.ndarray) — 要重新缩放的图像。
  • scale (float) — 用于重新缩放图像的缩放比例。
  • data_format (ChannelDimension,可选) — 图像的通道维度格式。如果未提供,则与输入图像相同。
  • dtype (np.dtype,可选,默认为 np.float32) — 输出图像的 dtype。默认为 np.float32。用于与特征提取器保持向后兼容。
  • input_data_format (ChannelDimension,可选) — 输入图像的通道维度格式。如果未提供,将从输入图像中推断。

返回值

np.ndarray

重新缩放后的图像。

按 scale 对 image 进行重新缩放。

transformers.image_transforms.resize

< >

( image: ndarraysize: tuple[int, int]resample: typing.Optional[ForwardRef('PILImageResampling')] = Nonereducing_gap: int | None = Nonedata_format: transformers.image_utils.ChannelDimension | None = Nonereturn_numpy: bool = Trueinput_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → np.ndarray

参数

  • image (np.ndarray) — 要调整大小的图像。
  • size (tuple[int, int]) — 用于调整图像大小的尺寸。
  • resample (int,可选,默认为 PILImageResampling.BILINEAR) — 用于重采样的滤波器。
  • reducing_gap (int, 可选) — 通过两步调整图像大小来应用优化。reducing_gap 越大,结果越接近公平重采样。有关更多详细信息,请参阅相应的 Pillow 文档。
  • data_format (ChannelDimension,可选) — 输出图像的通道维度格式。如果未设置,将使用从输入推断出的格式。
  • return_numpy (bool,可选,默认为 True) — 是否以 numpy 数组的形式返回调整大小后的图像。如果为 False,则返回一个 PIL.Image.Image 对象。
  • input_data_format (ChannelDimension,可选) — 输入图像的通道维度格式。如果未设置,将使用从输入中推断出的格式。

返回值

np.ndarray

调整大小后的图像。

使用 PIL 库将 image 调整为 size 指定的 (height, width)。

transformers.image_transforms.to_pil_image

< >

( image: typing.Union[numpy.ndarray, ForwardRef('PIL.Image.Image'), ForwardRef('torch.Tensor')]do_rescale: bool | None = Noneimage_mode: str | None = Noneinput_data_format: str | transformers.image_utils.ChannelDimension | None = None ) → PIL.Image.Image

参数

  • image (PIL.Image.Image 或 numpy.ndarray 或 torch.Tensor) — 要转换为 PIL.Image 格式的图像。
  • do_rescale (bool, 可选) — 是否应用缩放因子(将像素值转换为 0 到 255 之间的整数)。如果图像类型为浮点类型,且转换为 int 会导致精度损失,则默认值为 True;否则为 False。
  • image_mode (str, 可选) — 用于 PIL 图像的 mode。如果未设置,将使用输入图像类型的默认 mode。
  • input_data_format (ChannelDimension,可选) — 输入图像的通道维度格式。如果未设置,将使用从输入中推断出的格式。

返回值

PIL.Image.Image

转换后的图像。

将 image 转换为 PIL Image。如有需要,可选择对其进行重新缩放,并将通道维度移回最后一个轴。

ImageProcessingMixin

class transformers.ImageProcessingMixin

< >

( **kwargs )

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

fetch_images

< >

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

将单个 URL 或 URL 列表转换为对应的 PIL.Image 对象。

如果传入单个 url,返回值将是一个对象。如果传入一个列表,则返回一个对象列表。

from_dict

< >

( image_processor_dict: dict[str, typing.Any]**kwargs ) → ImageProcessingMixin

参数

  • image_processor_dict (dict[str, Any]) — 用于实例化图像处理器对象的字典。可以通过调用 to_dict() 方法从预训练检查点中获取此类字典。
  • kwargs (dict[str, Any]) — 用于初始化图像处理器对象的其他参数。

从这些参数实例化的图像处理器对象。

从 Python 参数字典实例化 ImageProcessingMixin 的一种类型。

from_json_file

< >

( json_file: str | os.PathLike ) → A image processor of type ImageProcessingMixin

参数

  • json_file (str 或 os.PathLike) — 包含参数的 JSON 文件的路径。

返回值

类型为 ImageProcessingMixin 的图像处理器

从该 JSON 文件实例化的 image_processor 对象。

从参数 JSON 文件的路径实例化一个 ImageProcessingMixin 类型的图像处理器。

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}

get_image_processor_dict

< >

( pretrained_model_name_or_path: str | os.PathLike**kwargs ) → tuple[Dict, Dict]

参数

  • pretrained_model_name_or_path (str 或 os.PathLike) — 我们想要从中获取参数字典的预训练检查点的标识符。
  • subfolder (str,可选,默认为 "") — 如果相关文件位于 huggingface.co 上模型仓库的子文件夹中,您可以在此处指定该文件夹的名称。
  • image_processor_filename (str,可选,默认为 "config.json") — 模型目录中用于图像处理器配置的文件名。

返回值

tuple[Dict, Dict]

用于实例化图像处理器对象的字典。

从 pretrained_model_name_or_path 解析为参数字典,用于使用 from_dict 实例化类型为 ~image_processor_utils.ImageProcessingMixin 的图像处理器。

push_to_hub

< >

( repo_id: strcommit_message: str | None = Nonecommit_description: str | None = Noneprivate: bool | None = Nonetoken: bool | str | None = Nonerevision: str | None = Nonecreate_pr: bool = Falsemax_shard_size: int | str | None = '50GB'tags: list[str] | None = None )

参数

  • repo_id (str) — 要推送图像处理器到的仓库名称。推送到特定组织时,应包含该组织的名称。
  • commit_message (str, 可选) — 推送时提交的提交信息。默认值为 "Upload image processor"。
  • commit_description (str, 可选) — 将创建的提交的描述
  • private (bool,可选) — 是否将仓库设为私有。如果为 None(默认值),除非组织的默认设置为私有,否则仓库将是公开的。如果仓库已存在,则忽略此值。
  • token (bool 或 str,可选) — 用于远程文件的 HTTP bearer 授权令牌。如果为 True(默认值),将使用运行 hf auth login 时生成的令牌(存储在 ~/.huggingface 中)。
  • revision (str, 可选) — 要推送上传文件的目标分支。
  • create_pr (bool,可选,默认为 False) — 是否使用上传的文件创建 PR,还是直接提交。
  • max_shard_size (int 或 str,可选,默认为 "50GB") — 仅适用于模型。分片前检查点的最大大小。分片后的每个检查点大小都将小于该值。如果以字符串形式表示,则必须为数字后跟单位(例如 "5MB")。
  • tags (list[str],可选) — 要推送到 Hub 的标签列表。

将图像处理器文件上传到 🤗 Model 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' )

参数

  • auto_class (str 或 type,可选,默认为 "AutoImageProcessor ") — 用于将此新图像处理器注册到的自动类。

将此类注册到指定的 auto 类中。此操作仅应针对自定义图像处理器使用,因为库中已有的图像处理器已与 AutoImageProcessor 建立映射。

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() 类方法重新加载。

to_dict

< >

( ) → dict[str, Any]

返回值

dict[str, Any]

构成此图像处理器实例的所有属性的字典。

将此实例序列化为 Python 字典。

to_json_file

< >

( json_file_path: str | os.PathLike )

参数

  • json_file_path (str 或 os.PathLike) — 用于保存此 image_processor 实例参数的 JSON 文件路径。

将此实例保存到 JSON 文件中。

to_json_string

< >

( ) → str

返回值

str

包含构成此 feature_extractor 实例的所有属性的字符串,采用 JSON 格式。

将此实例序列化为 JSON 字符串。

Update on GitHub