Transformers 文档

ViTMatte

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

ViTMatte

PyTorch

概述

ViTMatte 模型由 Jingfeng Yao、Xinggang Wang、Shusheng Yang 和 Baoyuan Wang 在论文 《Boosting Image Matting with Pretrained Plain Vision Transformers》 中提出。ViTMatte 利用普通的 Vision Transformer 来完成图像抠图任务,即精确估计图像和视频中的前景对象的过程。

论文摘要如下:

摘要:最近,普通视觉 Transformer (ViT) 由于其强大的建模能力和大规模预训练,在各种计算机视觉任务上表现出了令人印象深刻的性能。然而,它们尚未攻克图像抠图问题。我们假设图像抠图也可以通过 ViT 得到提升,并提出了一种新的高效且鲁棒的基于 ViT 的抠图系统,名为 ViTMatte。我们的方法利用 (i) 混合注意力机制与卷积颈部相结合,帮助 ViT 在抠图任务中实现出色的性能-计算权衡。(ii) 此外,我们引入了细节捕捉模块,该模块仅由简单的轻量级卷积组成,以补充抠图所需的详细信息。据我们所知,ViTMatte 是首个通过简洁的适配来释放 ViT 在图像抠图方面潜力的工作。它将 ViT 的许多优越特性继承到了抠图中,包括各种预训练策略、简洁的架构设计和灵活的推理策略。我们在 Composition-1k 和 Distinctions-646 这两个最常用的图像抠图基准上评估了 ViTMatte,我们的方法达到了最先进的性能,并大幅超越了先前的抠图工作。

此模型由 nielsr 贡献。原始代码可在此处找到。

drawing ViTMatte 顶层概览。图片来自原始论文

资源

一份官方 Hugging Face 和社区(由 🌎 标识)资源列表,帮助你开始使用 ViTMatte。

该模型期望同时输入图像和三元图(trimap)(拼接后)。请使用 ViTMatteImageProcessor 进行此操作。

VitMatteConfig

class transformers.VitMatteConfig

< >

( backbone_config: PretrainedConfig = None backbone = None use_pretrained_backbone = False use_timm_backbone = False backbone_kwargs = None hidden_size: int = 384 batch_norm_eps: float = 1e-05 initializer_range: float = 0.02 convstream_hidden_sizes: list = [48, 96, 192] fusion_hidden_sizes: list = [256, 128, 64, 32] **kwargs )

参数

  • backbone_config (PretrainedConfigdict, 可选, 默认为 VitDetConfig()) — 主干模型的配置。
  • backbone (str, 可选) — 当 backbone_configNone 时使用的主干名称。如果 use_pretrained_backboneTrue,将从 timm 或 transformers 库中加载相应的预训练权重。如果 use_pretrained_backboneFalse,将加载主干的配置并用其初始化具有随机权重的主干。
  • use_pretrained_backbone (bool, 可选, 默认为 False) — 是否为主干使用预训练权重。
  • use_timm_backbone (bool, 可选, 默认为 False) — 是否从 timm 库加载 `backbone`。如果为 `False`,则从 transformers 库加载主干。
  • backbone_kwargs (dict, 可选) — 从检查点加载时传递给 AutoBackbone 的关键字参数,例如 `{'out_indices': (0, 1, 2, 3)}`。如果设置了 `backbone_config`,则不能指定此参数。
  • hidden_size (int, 可选, 默认为 384) — 解码器的输入通道数。
  • batch_norm_eps (float, 可选, 默认为 1e-05) — 批归一化层使用的 epsilon 值。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • convstream_hidden_sizes (list[int], 可选, 默认为 [48, 96, 192]) — ConvStream 模块的输出通道数。
  • fusion_hidden_sizes (list[int], 可选, 默认为 [256, 128, 64, 32]) — Fusion 模块的输出通道数。

这是用于存储 VitMatteForImageMatting 配置的配置类。它用于根据指定的参数实例化一个 ViTMatte 模型,定义模型架构。使用默认值实例化一个配置将产生与 ViTMatte hustvl/vitmatte-small-composition-1k 架构类似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。更多信息请阅读 PretrainedConfig 的文档。

示例

>>> from transformers import VitMatteConfig, VitMatteForImageMatting

>>> # Initializing a ViTMatte hustvl/vitmatte-small-composition-1k style configuration
>>> configuration = VitMatteConfig()

>>> # Initializing a model (with random weights) from the hustvl/vitmatte-small-composition-1k style configuration
>>> model = VitMatteForImageMatting(configuration)

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

to_dict

< >

( )

将此实例序列化为 Python 字典。覆盖默认的 to_dict()。返回:dict[str, any]:构成此配置实例的所有属性的字典。

VitMatteImageProcessor

class transformers.VitMatteImageProcessor

< >

( do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_pad: bool = True size_divisibility: int = 32 **kwargs )

参数

  • do_rescale (bool, 可选, 默认为 True) — 是否按指定的比例 rescale_factor 重新缩放图像。可在 `preprocess` 方法中通过 `do_rescale` 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果对图像进行重新缩放,则使用的缩放因子。可在 `preprocess` 方法中通过 `rescale_factor` 参数覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否对图像进行归一化。可在 `preprocess` 方法中通过 `do_normalize` 参数覆盖。
  • image_mean (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,长度与图像中的通道数相同。可在 `preprocess` 方法中通过 `image_mean` 参数覆盖。
  • image_std (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,长度与图像中的通道数相同。可在 `preprocess` 方法中通过 `image_std` 参数覆盖。
  • do_pad (bool, 可选, 默认为 True) — 是否对图像进行填充,以使宽度和高度可被 `size_divisibility` 整除。可在 `preprocess` 方法中通过 `do_pad` 参数覆盖。
  • size_divisibility (int, 可选, 默认为 32) — 图像的宽度和高度将被填充,以能被此数字整除。

构建一个 ViTMatte 图像处理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] trimaps: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None do_pad: typing.Optional[bool] = None size_divisibility: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • images (ImageInput) — 要预处理的图像。接受单个或一批像素值范围为 0 到 255 的图像。如果传入像素值在 0 到 1 之间的图像,请设置 `do_rescale=False`。
  • trimaps (ImageInput) — 要预处理的三元图(Trimap)。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否将图像值重新缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 `do_rescale` 设置为 `True`,则用于重新缩放图像的缩放因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否对图像进行归一化。
  • image_mean (floatlist[float], 可选, 默认为 self.image_mean) — 如果 `do_normalize` 设置为 `True`,则使用的图像均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 如果 `do_normalize` 设置为 `True`,则使用的图像标准差。
  • do_pad (bool, 可选, 默认为 self.do_pad) — 是否对图像进行填充。
  • size_divisibility (int, 可选, 默认为 self.size_divisibility) — 如果 `do_pad` 设置为 `True`,则将图像填充到的尺寸可除性。
  • return_tensors (strTensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • 未设置:返回一个 `np.ndarray` 列表。
    • TensorType.TENSORFLOW'tf':返回一个 `tf.Tensor` 类型的批处理。
    • TensorType.PYTORCH'pt':返回一个 `torch.Tensor` 类型的批处理。
    • TensorType.NUMPY'np':返回一个 `np.ndarray` 类型的批处理。
    • TensorType.JAX'jax':返回一个 `jax.numpy.ndarray` 类型的批处理。
  • data_format (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。

预处理一张或一批图像。

VitMatteImageProcessorFast

class transformers.VitMatteImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.vitmatte.image_processing_vitmatte_fast.VitMatteFastImageProcessorKwargs] )

构建一个快速 VitMatte 图像处理器。

preprocess

< >

( images: list trimaps: list **kwargs: typing_extensions.Unpack[transformers.models.vitmatte.image_processing_vitmatte_fast.VitMatteFastImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • images (list) — 要预处理的图像。需要单个或一批像素值范围为 0 到 255 的图像。如果传入的图像像素值在 0 和 1 之间,请设置 do_rescale=False
  • trimaps (list) — 要预处理的三分图(trimap)。
  • 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:图像格式为(通道数, 高度, 宽度)。
    • "channels_last"ChannelDimension.LAST:图像格式为(高度, 宽度, 通道数)。
    • "none"ChannelDimension.NONE:图像格式为(高度, 宽度)。
  • device (torch.device, optional) — 用于处理图像的设备。如果未设置,则从输入图像中推断设备。
  • disable_grouping (bool, optional) — 是否禁用按尺寸分组图像,以单独处理而非批量处理。如果为 None,如果图像在 CPU 上,则设置为 True,否则设置为 False。此选择基于经验观察,详情见:https://github.com/huggingface/transformers/pull/38157
  • do_pad (bool, optional, 默认为 True) — 是否填充图像,使宽度和高度可被 size_divisibility 整除。可被 preprocess 方法中的 do_pad 参数覆盖。
  • size_divisibility (int, optional, 默认为 32) — 图像的宽度和高度将被填充,以能被该数字整除。

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

VitMatteForImageMatting

class transformers.VitMatteForImageMatting

< >

( config )

参数

  • config (VitMatteForImageMatting) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型相关的权重,只会加载配置。请查阅 from_pretrained() 方法来加载模型权重。

ViTMatte 框架利用任何视觉骨干网络,例如用于 ADE20k、CityScapes。

该模型继承自 PreTrainedModel。请查阅超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

该模型也是一个 PyTorch torch.nn.Module 的子类。可以像常规 PyTorch 模块一样使用它,并参考 PyTorch 文档了解所有与常规用法和行为相关的事项。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None labels: typing.Optional[torch.Tensor] = None return_dict: typing.Optional[bool] = None )

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)optional) — 与输入图像对应的张量。像素值可以使用 {image_processor_class} 获得。详情请参见 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • output_attentions (bool, optional) — 是否返回所有注意力层的注意力张量。更多细节请参见返回张量下的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。更多细节请参见返回张量下的 hidden_states
  • labels (torch.LongTensor,形状为 (batch_size, height, width)optional) — 用于计算损失的真实图像抠图(ground truth image matting)。
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通的元组。

VitMatteForImageMatting 的前向方法,覆盖了 `__call__` 特殊方法。

尽管前向传递的流程需要在此函数内定义,但之后应调用 `Module` 实例而不是此函数,因为前者会处理预处理和后处理步骤,而后者会静默忽略它们。

示例

>>> from transformers import VitMatteImageProcessor, VitMatteForImageMatting
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub import hf_hub_download

>>> processor = VitMatteImageProcessor.from_pretrained("hustvl/vitmatte-small-composition-1k")
>>> model = VitMatteForImageMatting.from_pretrained("hustvl/vitmatte-small-composition-1k")

>>> filepath = hf_hub_download(
...     repo_id="hf-internal-testing/image-matting-fixtures", filename="image.png", repo_type="dataset"
... )
>>> image = Image.open(filepath).convert("RGB")
>>> filepath = hf_hub_download(
...     repo_id="hf-internal-testing/image-matting-fixtures", filename="trimap.png", repo_type="dataset"
... )
>>> trimap = Image.open(filepath).convert("L")

>>> # prepare image + trimap for the model
>>> inputs = processor(images=image, trimaps=trimap, return_tensors="pt")

>>> with torch.no_grad():
...     alphas = model(**inputs).alphas
>>> print(alphas.shape)
torch.Size([1, 1, 640, 960])
< > 在 GitHub 上更新