Transformers documentation

EfficientLoFTR

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

and get access to the augmented documentation experience

to get started

该模型于 2024-03-07 在 HF papers 上发布,并于 2025-07-22 贡献至 Hugging Face Transformers。

PyTorch

EfficientLoFTR

EfficientLoFTR 是一种高效的无检测器局部特征匹配方法,能够以接近稀疏匹配的速度在图像间生成半稠密匹配。它在原始 LoFTR 架构的基础上,针对效率和精度进行了显著改进。其核心创新在于一种结合自适应 token 选择的聚合注意力机制,使模型速度比 LoFTR 快约 2.5 倍,同时实现了更高的精度。EfficientLoFTR 在速度上甚至能够超越 SuperPoint + LightGlue 等最先进的高效稀疏匹配流水线,因此适用于图像检索和 3D 重建等大规模或对延迟敏感的应用场景。

该模型由 stevenbucaille 贡献。

点击右侧边栏中的 EfficientLoFTR 模型,以查看将 EfficientLoFTR 应用于不同计算机视觉任务的更多示例。

以下示例演示了如何使用 Pipeline 或 AutoModel 类在两张图像之间匹配关键点。

Pipeline
AutoModel
from transformers import pipeline


keypoint_matcher = pipeline(task="keypoint-matching", model="zju-community/efficientloftr")

url_0 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_98169888_3347710852.jpg"
url_1 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_26757027_6717084061.jpg"

results = keypoint_matcher([url_0, url_1], threshold=0.9)
print(results[0])
# {'keypoint_image_0': {'x': ..., 'y': ...}, 'keypoint_image_1': {'x': ..., 'y': ...}, 'score': ...}

备注

  • EfficientLoFTR 旨在保持高精度的同时提升效率。它采用聚合注意力机制与自适应 token 选择,相较于原始 LoFTR 降低了计算开销。

    from transformers import AutoImageProcessor, AutoModelForKeypointMatching
    import torch
    from PIL import Image
    import requests
    
    processor = AutoImageProcessor.from_pretrained("zju-community/efficientloftr")
    model = AutoModelForKeypointMatching.from_pretrained("zju-community/efficientloftr", device_map="auto")
    
    # EfficientLoFTR requires pairs of images
    images = [image1, image2]
    inputs = processor(images, return_tensors="pt").to(model.device)
    with torch.inference_mode():
        outputs = model(**inputs)
    
    # Extract matching information
    keypoints = outputs.keypoints        # Keypoints in both images
    matches = outputs.matches            # Matching indices 
    matching_scores = outputs.matching_scores  # Confidence scores
  • 该模型生成半稠密匹配,在匹配密度与计算效率之间取得了良好的平衡。它在处理大视角变化和纹理匮乏的场景方面表现出色。

  • 为了更直观地可视化和分析,请使用 post_process_keypoint_matching() 方法以更易读的格式获取匹配结果。

    # Process outputs for visualization
    image_sizes = [[(image.height, image.width) for image in images]]
    processed_outputs = processor.post_process_keypoint_matching(outputs, image_sizes, threshold=0.2)
    
    for i, output in enumerate(processed_outputs):
        print(f"For the image pair {i}")
        for keypoint0, keypoint1, matching_score in zip(
                output["keypoints0"], output["keypoints1"], output["matching_scores"]
        ):
            print(f"Keypoint at {keypoint0.numpy()} matches with keypoint at {keypoint1.numpy()} with score {matching_score}")
  • 使用内置的绘图功能可视化图像之间的匹配情况。

    # Easy visualization using the built-in plotting method
    visualized_images = processor.visualize_keypoint_matching(images, processed_outputs)
  • EfficientLoFTR 采用了一种新颖的两阶段相关性层,以实现精确的亚像素对应,从而改进了原始 LoFTR 的细粒度相关性模块。

资源

EfficientLoFTRConfig

class transformers.EfficientLoFTRConfig

< >

( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: str | torch.dtype | None = Nonechunk_size_feed_forward: int = 0is_encoder_decoder: bool = Falseid2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = Nonestage_num_blocks: list[int] | None = Noneout_features: list[int] | None = Nonestage_stride: list[int] | None = Nonehidden_size: int = 256activation_function: str = 'relu'q_aggregation_kernel_size: int = 4kv_aggregation_kernel_size: int = 4q_aggregation_stride: int = 4kv_aggregation_stride: int = 4num_attention_layers: int = 4num_attention_heads: int = 8attention_dropout: float | int = 0.0attention_bias: bool = Falsemlp_activation_function: str = 'leaky_relu'coarse_matching_skip_softmax: bool = Falsecoarse_matching_threshold: float = 0.2coarse_matching_temperature: float = 0.1coarse_matching_border_removal: int = 2fine_kernel_size: int = 8batch_norm_eps: float = 1e-05rope_parameters: dict | None = Nonefine_matching_slice_dim: int = 8fine_matching_regress_temperature: float = 10.0initializer_range: float = 0.02 )

参数

  • stage_num_blocks (List,可选,默认为 [1, 2, 4, 14]) — 每个阶段中的块数
  • out_features (list[int], 可选) — 要从 backbone 返回的中间隐藏状态(特征图)的名称。可以是 "stem"、 "stage1"、"stage2" 等。
  • stage_stride (List,可选,默认为 [2, 1, 2, 2]) — 每个阶段使用的步长
  • hidden_size (int,可选,默认为 256) — 隐藏表示的维度。
  • activation_function (str,可选,默认为 relu) — 解码器中的非线性激活函数(函数或字符串)。例如,"gelu"、"relu"、"silu" 等。
  • q_aggregation_kernel_size (int,可选,默认为 4) — 融合网络中查询状态聚合的卷积核大小
  • kv_aggregation_kernel_size (int, 可选,默认为 4) — 融合网络中键和值状态聚合的卷积核大小
  • q_aggregation_stride (int,可选,默认为 4) — 融合网络中查询状态聚合的步长
  • kv_aggregation_stride (int,可选,默认值为 4) — 融合网络中键和值状态聚合的步长
  • num_attention_layers (int, 可选,默认为 4) — LocalFeatureTransformer 中注意力层的数量
  • num_attention_heads (int,可选,默认为 8) — Transformer 解码器中每个注意力层的注意力头数量。
  • attention_dropout (Union[float, int],可选,默认为 0.0) — 注意力概率的 dropout 比率。
  • attention_bias (bool,可选,默认为 False) — 在自注意力机制中,是否在 query、key、value 和 output 投影层中使用偏置。
  • mlp_activation_function (str, 可选,默认为 "leaky_relu") — 注意力 mlp 层中使用的激活函数。
  • coarse_matching_skip_softmax (bool,可选,默认为 False) — 是否在粗匹配步骤中跳过 softmax。
  • coarse_matching_threshold (float,可选,默认为 0.2) — 匹配所需的最低分数阈值。
  • coarse_matching_temperature (float,可选,默认值为 0.1) — 应用于粗粒度相似度矩阵的温度
  • coarse_matching_border_removal (int,可选,默认为 2) — 在粗略匹配过程中要移除的边框大小
  • fine_kernel_size (int,可选,默认为 8) — 用于精细特征匹配的核大小
  • batch_norm_eps (float,可选,默认值为 1e-05) — 批归一化层所使用的 epsilon
  • rope_parameters (dict, 可选) — 包含 RoPE 嵌入配置参数的字典。该字典应包含 rope_theta 的值,并且如果希望使用 RoPE 处理更长的 max_position_embeddings,则可选地包含用于缩放的参数。
  • fine_matching_slice_dim (int, 可选,默认为 8) — 用于将细粒度特征划分为第一阶段和第二阶段细粒度匹配的切片大小。
  • fine_matching_regress_temperature (float,可选,默认值为 10.0) — 应用于细粒度相似度矩阵的温度
  • initializer_range (float,可选,默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。

这是用于存储 EfficientLoFTRModel 配置的类。它根据指定的参数实例化 Efficientloftr 模型,并定义模型架构。使用默认值实例化配置将得到与 zju-community/efficientloftr 类似的配置。

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

示例:

>>> from transformers import EfficientLoFTRConfig, EfficientLoFTRForKeypointMatching

>>> # Initializing a EfficientLoFTR configuration
>>> configuration = EfficientLoFTRConfig()

>>> # Initializing a model from the EfficientLoFTR configuration
>>> model = EfficientLoFTRForKeypointMatching(configuration)

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

EfficientLoFTRImageProcessor

class transformers.EfficientLoFTRImageProcessor

< >

( **kwargs: *<class 'transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为 {'height' -- 480, 'width': 640}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 None) — 是否对图像进行归一化。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • do_grayscale (bool,kwargs,可选,默认为 self.do_grayscale) — 是否将图像转换为灰度图。可通过 preprocess 方法中的 do_grayscale 进行覆盖。

构建一个 EfficientLoFTRImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.efficientloftr.image_processing_efficientloftr.EfficientLoFTRImageProcessorKwargs'> ) → ~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_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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • do_grayscale (bool,kwargs,可选,默认为 self.do_grayscale) — 是否将图像转换为灰度图。可通过 preprocess 方法中的 do_grayscale 进行覆盖。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

post_process_keypoint_matching

< >

( outputs: EfficientLoFTRKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → List[Dict]

参数

  • outputs (EfficientLoFTRKeypointMatchingOutput) — 模型的原始输出。
  • target_sizes (torch.Tensor 或 List[Tuple[Tuple[int, int]]],可选) — 形状为 (batch_size, 2, 2) 的张量,或包含元组列表(Tuple[int, int]),其中包含批次中每张图片的目标尺寸 (height, width)。这必须是原始图像尺寸(在任何处理之前)。
  • threshold (float,可选,默认值为 0.0) — 用于过滤低分匹配项的阈值。

返回值

List[Dict]

一个字典列表,每个字典包含该图像对中第一张和第二张图像的关键点、匹配分数以及匹配索引。

将 EfficientLoFTRKeypointMatchingOutput 的原始输出转换为关键点、分数和描述符列表,其坐标为相对于原始图像尺寸的绝对坐标。

visualize_keypoint_matching

< >

( imageskeypoint_matching_output: list ) → List[PIL.Image.Image]

参数

  • images — 要绘制的图像对。与 EfficientLoFTRImageProcessor.preprocess 相同。期望输入为包含 2 张图像的列表,或包含 2 张图像列表的列表,像素值范围为 0 到 255。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 经过后处理的特征点匹配输出

返回值

List[PIL.Image.Image]

一个 PIL 图像列表,每个图像并排显示图像对,并包含检测到的关键点以及它们之间的匹配关系。

并排绘制图像对,同时显示检测到的关键点以及它们之间的匹配关系。

EfficientLoFTRImageProcessorPil

class transformers.EfficientLoFTRImageProcessorPil

< >

( **kwargs: *<class 'transformers.models.efficientloftr.image_processing_pil_efficientloftr.EfficientLoFTRImageProcessorKwargs'> )

参数

  • do_convert_rgb (bool,kwargs,可选) — 是否将图像转换为 RGB。
  • do_resize (bool,kwargs,可选,默认为 True) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None],kwargs,默认为 {'height' -- 480, 'width': 640}): 描述输入到模型的最大尺寸。
  • default_to_square (bool,kwargs,可选,默认为 False) — 当 size 为 int 时,是否在调整大小时默认使用正方形图像。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None], kwargs) — 应用 center_crop 后输出图像的尺寸。
  • resample (Annotated[Union[int, PILImageResampling, NoneType], None], kwargs,默认为 2) — 如果调整图像大小,则使用的重采样滤波器。它可以是枚举 PILImageResampling 中的一个值。仅当 do_resize 设置为 True 时才会生效。
  • do_rescale (bool,kwargs,可选,默认为 True) — 是否对图像进行重新缩放。
  • rescale_factor (float,kwargs,可选,默认为 0.00392156862745098) — 当 do_rescale 设置为 True 时,用于对图像进行缩放的缩放因子。
  • do_normalize (bool,kwargs,可选,默认为 None) — 是否对图像进行归一化。
  • 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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • do_grayscale (bool,kwargs,可选,默认为 self.do_grayscale) — 是否将图像转换为灰度图。可通过 preprocess 方法中的 do_grayscale 进行覆盖。

构建一个 EfficientLoFTRImageProcessor 图像处理器。

预处理

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: *<class 'transformers.models.efficientloftr.image_processing_pil_efficientloftr.EfficientLoFTRImageProcessorKwargs'> ) → ~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_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 数量。 为向后兼容而添加,但在未来的模型中,应将其设置为处理器的属性。
  • do_grayscale (bool,kwargs,可选,默认为 self.do_grayscale) — 是否将图像转换为灰度图。可通过 preprocess 方法中的 do_grayscale 进行覆盖。

返回值

~image_processing_base.BatchFeature

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(如 ‘pixel_values’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处指定 tensor_type,以便在初始化时将 PyTorch/Numpy 张量中的整数列表进行转换。

post_process_keypoint_matching

< >

( outputs: EfficientLoFTRKeypointMatchingOutputtarget_sizes: transformers.utils.generic.TensorType | list[tuple]threshold: float = 0.0 ) → List[Dict]

参数

  • outputs (EfficientLoFTRKeypointMatchingOutput) — 模型的原始输出。
  • target_sizes (torch.Tensor 或 List[Tuple[Tuple[int, int]]],可选) — 形状为 (batch_size, 2, 2) 的张量,或包含元组列表(Tuple[int, int]),其中包含批次中每张图片的目标尺寸 (height, width)。这必须是原始图像尺寸(在任何处理之前)。
  • threshold (float,可选,默认值为 0.0) — 用于过滤低分匹配项的阈值。

返回值

List[Dict]

一个字典列表,每个字典包含该图像对中第一张和第二张图像的关键点、匹配分数以及匹配索引。

将 EfficientLoFTRKeypointMatchingOutput 的原始输出转换为关键点、分数和描述符列表,其坐标为相对于原始图像尺寸的绝对坐标。

visualize_keypoint_matching

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]keypoint_matching_output: list ) → List[PIL.Image.Image]

参数

  • images (ImageInput) — 要绘制的图像对。与 EfficientLoFTRImageProcessor.preprocess 相同。期望输入为包含 2 张图像的列表,或包含 2 张图像列表的列表,像素值范围为 0 到 255。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]) — 经过后处理的特征点匹配输出

返回值

List[PIL.Image.Image]

一个 PIL 图像列表,每个图像并排显示图像对,并包含检测到的关键点以及它们之间的匹配关系。

并排绘制图像对,同时显示检测到的关键点以及它们之间的匹配关系。

EfficientLoFTRModel

class transformers.EfficientLoFTRModel

< >

( config: EfficientLoFTRConfig )

参数

  • config (EfficientLoFTRConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

EfficientLoFTR 模型以图像作为输入,并输出图像的特征。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensorlabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → BackboneOutput or tuple(torch.Tensor)

参数

  • pixel_values (torch.Tensor,形状为 (batch_size, num_channels, image_size, image_size)) — 与输入图像对应的张量。可以使用 EfficientLoFTRImageProcessor 获取像素值。有关详细信息,请参阅 EfficientLoFTRImageProcessor.call()(processor_class 使用 EfficientLoFTRImageProcessor 处理图像)。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。

返回值

BackboneOutput 或 tuple(torch.Tensor)

BackboneOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),其包含的元素取决于配置(EfficientLoFTRConfig)和输入。

EfficientLoFTRModel 的 forward 方法会重写 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • feature_maps(形状为 (batch_size, num_channels, height, width) 的 tuple(torch.Tensor))— 各阶段的特征图。

  • hidden_states (tuple(torch.Tensor),可选,在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回) — 一个 torch.Tensor 元组(包含嵌入层的输出以及每一层的输出),形状为 (batch_size, sequence_length, hidden_size) 或 (batch_size, num_channels, height, width),具体取决于骨干网络。

    模型在每个阶段输出处的隐藏状态,以及初始嵌入输出。

  • attentions (tuple(torch.Tensor),可选,当传入 output_attentions=True 或 config.output_attentions=True 时返回) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, num_heads, sequence_length, sequence_length)。仅当主干网络使用注意力机制时适用。

    注意力权重,即经过注意力 softmax 之后的权重,用于在自注意力头中计算加权平均值。

示例:

>>> from transformers import AutoImageProcessor, AutoModel
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_78916675_4568141288.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image1 = Image.open(BytesIO(response.read()))

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_19481797_2295892421.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image2 = Image.open(BytesIO(response.read()))

>>> images = [image1, image2]

>>> processor = AutoImageProcessor.from_pretrained("zju-community/efficient_loftr")
>>> model = AutoModel.from_pretrained("zju-community/efficient_loftr")

>>> with torch.no_grad():
>>>     inputs = processor(images, return_tensors="pt")
>>>     outputs = model(**inputs)

EfficientLoFTRForKeypointMatching

class transformers.EfficientLoFTRForKeypointMatching

< >

( config: EfficientLoFTRConfig )

参数

  • config (EfficientLoFTRConfig) — 模型配置类,包含模型的所有参数。使用配置文件进行初始化时,不会加载与模型关联的权重,仅加载配置。请查看 from_pretrained() 方法以加载模型权重。

EfficientLoFTR 模型以图像作为输入,并输出它们之间的匹配结果。

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

该模型也是 PyTorch torch.nn.Module 的子类。 请将其作为常规的 PyTorch Module 使用,有关通用用法和行为的所有事项,请参阅 PyTorch 文档。

forward

< >

( pixel_values: Tensorlabels: typing.Optional[torch.LongTensor] = None**kwargs: *<class 'transformers.utils.generic.TransformersKwargs'> ) → EfficientLoFTRKeypointMatchingOutput or tuple(torch.Tensor)

参数

  • pixel_values(形状为 (batch_size, num_channels, image_size, image_size) 的 torch.Tensor)— 对应于输入图像的张量。可以使用 image_processor_class 获取像素值。有关详细信息,请参阅 image_processor_class.__call__(processor_class 使用 image_processor_class 来处理图像)。
  • labels (torch.LongTensor,形状为 (batch_size, sequence_length),可选) — 用于计算掩码语言建模损失的标签。索引值应在 [0, ..., config.vocab_size] 范围内,或为 -100(参见 input_ids 的文档字符串)。索引值设为 -100 的 token 将被忽略(即被掩码),损失仅针对标签位于 [0, ..., config.vocab_size] 范围内的 token 进行计算。

返回值

EfficientLoFTRKeypointMatchingOutput 或 tuple(torch.Tensor)

EfficientLoFTRKeypointMatchingOutput 或 torch.Tensor 元组(如果传入 return_dict=False 或 config.return_dict=False),包含根据配置(None)和输入而定的各种元素。

EfficientLoFTRForKeypointMatching 的 forward 方法重写了 __call__ 特殊方法。

尽管前向传播的实现需要在此函数中定义,但之后应调用 Module 实例,而不是直接调用此函数,因为前者会负责执行预处理和后处理步骤,而后者则会静默地忽略这些步骤。

  • loss (torch.Tensor,形状为 (1,),可选) — 训练期间计算的损失。
  • matches(形状为 (batch_size, 2, num_matches) 的 torch.Tensor)— 在另一张图像中匹配到的关键点索引。
  • matching_scores(形状为 (batch_size, 2, num_matches) 的 torch.Tensor)— 预测匹配项的分数。
  • keypoints(形状为 (batch_size, num_keypoints, 2) 的 torch.Tensor)— 给定图像中预测关键点(keypoints)的绝对 (x, y) 坐标。
  • hidden_states (tuple[torch.Tensor, ...],可选) — 一个 torch.Tensor 元组(每个阶段一个输出),形状为 (batch_size, 2, num_channels, num_keypoints),在传入 output_hidden_states=True 或 config.output_hidden_states=True 时返回
  • attentions (tuple[torch.Tensor, ...],可选) — 一个 torch.Tensor 元组(每层一个),形状为 (batch_size, 2, num_heads, num_keypoints, num_keypoints),在传入 output_attentions=True 或 config.output_attentions=True 时返回

示例:

>>> from transformers import AutoImageProcessor, AutoModel
>>> import torch
>>> from PIL import Image
>>> from huggingface_hub.utils import httpx
>>> from io import BytesIO

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_78916675_4568141288.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image1 = Image.open(BytesIO(response.read()))

>>> url = "https://github.com/magicleap/SuperGluePretrainedNetwork/blob/master/assets/phototourism_sample_images/london_bridge_19481797_2295892421.jpg?raw=true"
>>> with httpx.stream("GET", url) as response:
...     image2 = Image.open(BytesIO(response.read()))

>>> images = [image1, image2]

>>> processor = AutoImageProcessor.from_pretrained("zju-community/efficient_loftr")
>>> model = AutoModel.from_pretrained("zju-community/efficient_loftr")

>>> with torch.no_grad():
>>>     inputs = processor(images, return_tensors="pt")
>>>     outputs = model(**inputs)
Update on GitHub