Transformers 文档

LightGlue

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

LightGlue

概述

LightGlue 模型由 Philipp Lindenberger、Paul-Edouard Sarlin 和 Marc Pollefeys 在 LightGlue: Local Feature Matching at Light Speed 中提出。

SuperGlue 类似,该模型包含匹配从两幅图像中提取的两组局部特征,其目标是比 SuperGlue 更快。与 SuperPoint 模型 结合使用时,它可以用于匹配两幅图像并估计它们之间的姿态。该模型适用于图像匹配、单应性估计等任务。

论文摘要如下:

我们引入了 LightGlue,一个学习跨图像匹配局部特征的深度神经网络。我们重新审视了稀疏匹配领域最先进的 SuperGlue 的多项设计决策,并推导出了简单但有效的改进。这些改进共同使得 LightGlue 在内存和计算方面更高效,更准确,并且更容易训练。一个关键特性是 LightGlue 能够适应问题的难度:对于直观上更容易匹配的图像对(例如,由于较大的视觉重叠或有限的外观变化),推理速度会快得多。这为在 3D 重建等对延迟敏感的应用中部署深度匹配器开辟了令人兴奋的前景。代码和训练好的模型可在 此 URL 公开获取。

如何使用

以下是使用该模型的一个快速示例。由于该模型是一个图像匹配模型,它需要成对的图像进行匹配。原始输出包含关键点检测器检测到的关键点列表以及匹配及其相应的匹配分数列表。

from transformers import AutoImageProcessor, AutoModel
import torch
from PIL import Image
import requests

url_image1 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_98169888_3347710852.jpg"
image1 = Image.open(requests.get(url_image1, stream=True).raw)
url_image2 = "https://raw.githubusercontent.com/magicleap/SuperGluePretrainedNetwork/refs/heads/master/assets/phototourism_sample_images/united_states_capitol_26757027_6717084061.jpg"
image2 = Image.open(requests.get(url_image2, stream=True).raw)

images = [image1, image2]

processor = AutoImageProcessor.from_pretrained("ETH-CVG/lightglue_superpoint")
model = AutoModel.from_pretrained("ETH-CVG/lightglue_superpoint")

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

您可以使用 `LightGlueImageProcessor` 中的 `post_process_keypoint_matching` 方法以可读格式获取关键点和匹配。

image_sizes = [[(image.height, image.width) for image in images]]
outputs = processor.post_process_keypoint_matching(outputs, image_sizes, threshold=0.2)
for i, output in enumerate(outputs):
    print("For the image pair", i)
    for keypoint0, keypoint1, matching_score in zip(
            output["keypoints0"], output["keypoints1"], output["matching_scores"]
    ):
        print(
            f"Keypoint at coordinate {keypoint0.numpy()} in the first image matches with keypoint at coordinate {keypoint1.numpy()} in the second image with a score of {matching_score}."
        )

您可以通过向此方法提供原始图像和输出,来可视化图像之间的匹配。

processor.plot_keypoint_matching(images, outputs)

image/png

该模型由 stevenbucaille 贡献。原始代码可以在这里找到。

LightGlueConfig

class transformers.LightGlueConfig

< >

( keypoint_detector_config: SuperPointConfig = None descriptor_dim: int = 256 num_hidden_layers: int = 9 num_attention_heads: int = 4 num_key_value_heads = None depth_confidence: float = 0.95 width_confidence: float = 0.99 filter_threshold: float = 0.1 initializer_range: float = 0.02 hidden_act: str = 'gelu' attention_dropout = 0.0 attention_bias = True **kwargs )

参数

  • keypoint_detector_config (Union[AutoConfig, dict], 可选, 默认为 SuperPointConfig) — 关键点检测器的配置对象或字典。
  • descriptor_dim (int, 可选, 默认为 256) — 描述符的维度。
  • num_hidden_layers (int, 可选, 默认为 9) — 自注意力和交叉注意力层的数量。
  • num_attention_heads (int, 可选, 默认为 4) — 多头注意力中的头数。
  • num_key_value_heads (int, 可选) — 用于实现分组查询注意力的键值头数量。如果 num_key_value_heads=num_attention_heads,模型将使用多头注意力 (MHA);如果 num_key_value_heads=1,模型将使用多查询注意力 (MQA),否则使用 GQA。当将多头检查点转换为 GQA 检查点时,每个分组键和值头应通过对其组内的所有原始头进行平均池化来构建。更多详情请参阅此论文。如果未指定,将默认为 num_attention_heads
  • depth_confidence (float, 可选, 默认为 0.95) — 用于执行早期停止的置信度阈值。
  • width_confidence (float, 可选, 默认为 0.99) — 用于修剪点的置信度阈值。
  • filter_threshold (float, 可选, 默认为 0.1) — 用于过滤低分匹配的置信度阈值。
  • initializer_range (float, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • hidden_act (str, 可选, 默认为 "gelu") — 隐藏层中使用的激活函数。
  • attention_dropout (float, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。
  • attention_bias (bool, 可选, 默认为 True) — 在自注意力过程中,是否在查询、键、值和输出投影层中使用偏置。

这是用于存储 LightGlueForKeypointMatching 配置的配置类。它用于根据指定参数实例化 LightGlue 模型,定义模型架构。使用默认值实例化配置将产生与 LightGlue ETH-CVG/lightglue_superpoint 架构类似的配置。

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

示例

>>> from transformers import LightGlueConfig, LightGlueForKeypointMatching

>>> # Initializing a LightGlue style configuration
>>> configuration = LightGlueConfig()

>>> # Initializing a model from the LightGlue style configuration
>>> model = LightGlueForKeypointMatching(configuration)

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

LightGlueImageProcessor

class transformers.LightGlueImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: float = 0.00392156862745098 do_grayscale: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 控制是否将图像的 (height, width) 尺寸调整为指定的 size。可在 preprocess 方法中通过 do_resize 覆盖。
  • size (dict[str, int] 可选, 默认为 {"height" -- 480, "width": 640}): 应用 resize 后输出图像的分辨率。仅在 do_resize 设置为 True 时有效。可在 preprocess 方法中通过 size 覆盖。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BILINEAR) — 如果调整图像大小,则使用的重采样滤波器。可在 preprocess 方法中通过 resample 覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否通过指定的 rescale_factor 重新缩放图像。可在 preprocess 方法中通过 do_rescale 覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可在 preprocess 方法中通过 rescale_factor 覆盖。
  • do_grayscale (bool, 可选, 默认为 True) — 是否将图像转换为灰度。可在 preprocess 方法中通过 do_grayscale 覆盖。

构建 LightGlue 图像处理器。

plot_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: LightGlueKeypointMatchingOutput )

参数

  • images (ImageInput) — 要绘制的图像对。与 LightGlueImageProcessor.preprocess 相同。期望是包含 2 张图像的列表或包含 2 张图像列表的列表,像素值范围为 0 到 255。
  • outputs (LightGlueKeypointMatchingOutput) — 模型的原始输出。

将图像对与检测到的关键点以及它们之间的匹配并排绘制出来。需要安装 matplotlib。

post_process_keypoint_matching

< >

( outputs: LightGlueKeypointMatchingOutput target_sizes: typing.Union[transformers.utils.generic.TensorType, list[tuple]] threshold: float = 0.0 ) list[Dict]

参数

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

返回

list[Dict]

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

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

preprocess

< >

( images do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_grayscale: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs )

参数

  • images (ImageInput) — 要预处理的图像对。期望是包含 2 张图像的列表或包含 2 张图像列表的列表,像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 self.size) — 应用 resize 后输出图像的尺寸。如果 size["shortest_edge"] >= 384,图像将调整为 (size["shortest_edge"], size["shortest_edge"])。否则,图像的较短边将匹配 int(size["shortest_edge"]/ crop_pct),然后将图像裁剪为 (size["shortest_edge"], size["shortest_edge"])。仅在 do_resize 设置为 True 时有效。
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 如果调整图像大小,要使用的重采样滤镜。可以是 PILImageResampling 的一种滤镜。仅当 do_resize 设置为 True 时有效。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否将图像值缩放到 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,用于缩放图像的缩放因子。
  • do_grayscale (bool, 可选, 默认为 self.do_grayscale) — 是否将图像转换为灰度。
  • 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)。

预处理一张或一批图像。

resize

< >

( 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]) — 形式为 {"height": int, "width": int} 的字典,指定输出图像的大小。
  • data_format (ChannelDimensionstr, 可选) — 输出图像的通道维度格式。如果未提供,将从输入图像推断。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。
  • 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)。

调整图像大小。

  • preprocess
  • post_process_keypoint_matching
  • plot_keypoint_matching

LightGlueForKeypointMatching

class transformers.LightGlueForKeypointMatching

< >

( config: LightGlueConfig )

参数

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

LightGlue 模型,以图像为输入,输出它们的匹配。

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

此模型也是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档以了解所有与一般使用和行为相关的事项。

forward

< >

( pixel_values: FloatTensor labels: typing.Optional[torch.LongTensor] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None ) transformers.models.lightglue.modeling_lightglue.LightGlueKeypointMatchingOutputtuple(torch.FloatTensor)

参数

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以通过 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • labels (形状为 (batch_size, sequence_length)torch.LongTensor, 可选) — 用于计算掩码语言模型损失的标签。索引应在 [0, ..., config.vocab_size] 或 -100 之间(请参阅 input_ids 文档字符串)。索引设置为 -100 的标记将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的标记计算。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。更多详细信息请参阅返回张量中的 attentions
  • output_hidden_states (bool, 可选) — 是否返回所有层的隐藏状态。更多详细信息请参阅返回张量中的 hidden_states

返回

transformers.models.lightglue.modeling_lightglue.LightGlueKeypointMatchingOutputtuple(torch.FloatTensor)

transformers.models.lightglue.modeling_lightglue.LightGlueKeypointMatchingOutputtorch.FloatTensor 的元组(如果传入 return_dict=Falseconfig.return_dict=False 时),包含根据配置(LightGlueConfig)和输入的不同元素。

  • loss (形状为 (1,)torch.FloatTensor可选) — 训练期间计算的损失。
  • matches (形状为 (batch_size, 2, num_matches)torch.FloatTensor) — 在另一图像中匹配的关键点索引。
  • matching_scores (形状为 (batch_size, 2, num_matches)torch.FloatTensor) — 预测匹配的分数。
  • keypoints (形状为 (batch_size, num_keypoints, 2)torch.FloatTensor) — 给定图像中预测关键点的绝对 (x, y) 坐标。
  • prune (形状为 (batch_size, num_keypoints)torch.IntTensor) — 剪枝掩码,指示哪些关键点被移除以及在哪个层被移除。
  • mask (形状为 (batch_size, num_keypoints)torch.BoolTensor) — 掩码,指示匹配、匹配分数、关键点和剪枝中的哪些值是关键点匹配信息。
  • hidden_states (Tuple[torch.FloatTensor, ...], 可选) — torch.FloatTensor 的元组(每个阶段的输出一个),形状为 (batch_size, 2, num_channels, num_keypoints),当传入 output_hidden_states=Trueconfig.output_hidden_states=True 时返回。
  • attentions (Tuple[torch.FloatTensor, ...], 可选) — torch.FloatTensor 的元组(每层一个),形状为 (batch_size, 2, num_heads, num_keypoints, num_keypoints),当传入 output_attentions=Trueconfig.output_attentions=True 时返回。

LightGlueForKeypointMatching forward 方法,覆盖了 __call__ 特殊方法。

尽管前向传播的配方需要在此函数中定义,但此后应调用 Module 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则默默地忽略它们。

  • forward
< > 在 GitHub 上更新