Transformers 文档

LightGlue

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

该模型于 2023-06-23 发布,并于 2025-06-17 添加到 Hugging Face Transformers。

PyTorch

LightGlue

LightGlue 是一种深度神经网络,可学习跨图像匹配局部特征。它重新审视了 SuperGlue 的多项设计决策,并进行了简单但有效的改进。总的来说,这些改进使得 LightGlue 在内存和计算方面都更高效,更准确,并且训练起来更容易。与 SuperGlue 类似,该模型由匹配从两张图像提取的两组局部特征组成,目标是比 SuperGlue 更快。与 SuperPoint 模型配合使用,它可以用于匹配两张图像并估计它们之间的姿态。

您可以在 ETH-CVG 组织下找到所有原始 LightGlue 检查点。

该模型由 stevenbucaille 贡献。

点击右侧边栏中的 LightGlue 模型,了解更多关于如何将 LightGlue 应用于不同计算机视觉任务的示例。

下面的示例演示了如何使用 PipelineAutoModel 类在两张图像之间匹配关键点。

流水线
自动模型
from transformers import pipeline

keypoint_matcher = pipeline(task="keypoint-matching", model="ETH-CVG/lightglue_superpoint")

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': ...}

注意事项

  • LightGlue 能够适应任务难度。对于直观上易于匹配的图像对(例如,由于更大的视觉重叠或有限的外观变化),推理速度要快得多。

    from transformers import AutoImageProcessor, AutoModel
    import torch
    from PIL import Image
    import requests
    
    processor = AutoImageProcessor.from_pretrained("ETH-CVG/lightglue_superpoint")
    model = AutoModel.from_pretrained("ETH-CVG/lightglue_superpoint")
    
    # LightGlue requires pairs of images
    images = [image1, image2]
    inputs = processor(images, return_tensors="pt")
    with torch.inference_mode():
        outputs = model(**inputs)
    
    # Extract matching information
    keypoints0 = outputs.keypoints0  # Keypoints in first image
    keypoints1 = outputs.keypoints1  # Keypoints in second image
    matches = outputs.matches        # Matching indices
    matching_scores = outputs.matching_scores  # Confidence scores
  • 与 SuperGlue 类似,但效率更高,该模型输出匹配索引、关键点和每个匹配的置信度分数。

  • 为了更好地可视化和分析,请使用 LightGlueImageProcessor.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
    processor.visualize_keypoint_matching(images, processed_outputs)

资源

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 trust_remote_code: bool = False **kwargs )

参数

  • keypoint_detector_config (Union[AutoConfig, dict], optional, defaults to SuperPointConfig) — 关键点检测器的配置对象或字典。
  • descriptor_dim (int, optional, defaults to 256) — 描述符的维度。
  • num_hidden_layers (int, optional, defaults to 9) — 自注意和交叉注意层的数量。
  • num_attention_heads (int, optional, defaults to 4) — 多头注意力中的头数。
  • num_key_value_heads (int, optional) — 这是实现分组查询注意力 (Grouped Query Attention) 所需的 key_value 头数。如果 num_key_value_heads=num_attention_heads,则模型将使用多头注意力 (MHA);如果 num_key_value_heads=1,则模型将使用多查询注意力 (MQA);否则使用 GQA。在将多头检查点转换为 GQA 检查点时,每个分组的键和值头应通过对该分组内的所有原始头进行平均池化来构造。有关更多详细信息,请参阅 此论文。如果未指定,将默认为 num_attention_heads
  • depth_confidence (float, optional, defaults to 0.95) — 用于执行提前停止的置信度阈值。
  • width_confidence (float, optional, defaults to 0.99) — 用于剪枝点的置信度阈值。
  • filter_threshold (float, optional, defaults to 0.1) — 用于过滤匹配的置信度阈值。
  • initializer_range (float, optional, defaults to 0.02) — 初始化所有权重矩阵的 truncated_normal_initializer 的标准差。
  • hidden_act (str, optional, defaults to "gelu") — 隐藏层中要使用的激活函数。
  • attention_dropout (float, optional, defaults to 0.0) — 注意力概率的 dropout 比率。
  • attention_bias (bool, optional, defaults to True) — 是否在自注意力期间使用查询、键、值和输出投影层的偏置。
  • trust_remote_code (bool, optional, defaults to False) — 在使用 SuperPoint 以外的模型作为关键点检测器时,是否信任远程代码。

这是用于存储 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: dict[str, int] | None = None resample: Resampling = <Resampling.BILINEAR: 2> do_rescale: bool = True rescale_factor: float = 0.00392156862745098 do_grayscale: bool = True **kwargs )

参数

  • do_resize (bool, optional, defaults to True) — Controls whether to resize the image’s (height, width) dimensions to the specified size. Can be overridden by do_resize in the preprocess method.
  • size (dict[str, int] optional, defaults to {"height" -- 480, "width": 640}): Resolution of the output image after resize is applied. Only has an effect if do_resize is set to True. Can be overridden by size in the preprocess method.
  • resample (PILImageResampling, optional, defaults to Resampling.BILINEAR) — Resampling filter to use if resizing the image. Can be overridden by resample in the preprocess method.
  • do_rescale (bool, optional, defaults to True) — Whether to rescale the image by the specified scale rescale_factor. Can be overridden by do_rescale in the preprocess method.
  • rescale_factor (int or float, optional, defaults to 1/255) — Scale factor to use if rescaling the image. Can be overridden by rescale_factor in the preprocess method.
  • do_grayscale (bool, optional, defaults to True) — Whether to convert the image to grayscale. Can be overridden by do_grayscale in the preprocess method.

构建一个 LightGlue 图像处理器。

preprocess

< >

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

参数

  • images (ImageInput) — 要预处理的图像对。期望值为包含 2 个图像的列表,或包含 2 个图像的列表的列表,像素值范围为 0 到 255。如果输入像素值在 0 到 1 之间,请将 do_rescale 设置为 False
  • do_resize (bool, optional, defaults to self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], optional, defaults to self.size) — 调整大小后的输出图像尺寸。如果 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, optional, defaults to self.resample) — 调整图像大小时使用的重采样滤波器。可以是 PILImageResamplingfilters 中的一个。仅在 do_resize 设置为 True 时生效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否将图像值重新缩放到 [0 - 1] 之间。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 如果设置 do_rescaleTrue,则用于缩放图像的缩放因子。
  • do_grayscale (bool, optional, defaults to self.do_grayscale) — 是否将图像转换为灰度。
  • return_tensors (str or TensorType, optional) — 要返回的张量类型。可以是以下之一:
    • 未设置:返回 np.ndarray 列表。
    • TensorType.PYTORCH'pt':返回 torch.Tensor 类型的批次。
    • TensorType.NUMPY'np':返回 np.ndarray 类型的批次。
  • data_format (ChannelDimension or str, optional, defaults to ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimension or str, optional) — 输入图像的通道维度格式。如果未设置,则通道维度格式将从输入图像推断。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像格式为 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:图像格式为 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:图像格式为 (height, width)。

预处理一张或一批图像。

post_process_keypoint_matching

< >

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

参数

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

返回

list[Dict]

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

LightGlueKeypointMatchingOutput 的原始输出转换为以原始图像尺寸为绝对坐标的关键点、得分和描述符列表。

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) — 要绘制的图像对。与 LightGlueImageProcessor.preprocess 相同。期望值为包含 2 个图像的列表,或包含 2 个图像的列表的列表,像素值范围为 0 到 255。
  • keypoint_matching_output (List[Dict[str, torch.Tensor]]]) — A post processed keypoint matching output

返回

List[PIL.Image.Image]

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

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

LightGlueImageProcessorFast

class transformers.LightGlueImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.lightglue.image_processing_lightglue.LightGlueImageProcessorKwargs] )

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

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.lightglue.image_processing_lightglue.LightGlueImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list, list, list]) — 要预处理的图像。期望是单个图像或图像批次,像素值范围为 0 到 255。如果传入的像素值范围在 0 到 1 之间,请将 do_rescale 设置为 False
  • do_convert_rgb (bool | None.do_convert_rgb) — 是否将图像转换为 RGB。
  • do_resize (bool | None.do_resize) — 是否调整图像大小。
  • size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 描述模型的最大输入尺寸。
  • crop_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 应用 center_crop 后输出图像的大小。
  • resample (Annotated[Union[PILImageResampling, int, NoneType], None]) — 调整图像大小时使用的重采样过滤器。它可以是 PILImageResampling 枚举之一。仅当 do_resize 设置为 True 时才有效。
  • do_rescale (bool | None.do_rescale) — 是否重新缩放图像。
  • rescale_factor (float | None.rescale_factor) — 如果设置了 do_rescale=True,则用于重新缩放图像的缩放因子。
  • do_normalize (bool | None.do_normalize) — 是否进行归一化。
  • image_mean (float | list[float] | tuple[float, ...] | None.image_mean) — 用于归一化的图像均值。仅当 do_normalize 设置为 True 时有效。
  • image_std (float | list[float] | tuple[float, ...] | None.image_std) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时有效。
  • do_pad (bool | None.do_pad) — 是否填充图像。填充是针对批次中最大的尺寸进行的,或者对每个图像进行固定大小的方形填充。确切的填充策略取决于模型。
  • pad_size (Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]) — 将图像填充到的大小({"height": int, "width" int})。必须大于预处理所提供的任何图像尺寸。如果未提供 pad_size,图像将被填充到批次中最大的高度和宽度。仅在 do_pad=True 时应用。
  • do_center_crop (bool | None.do_center_crop) — 是否中心裁剪图像。
  • data_format (str | ~image_utils.ChannelDimension | None.data_format) — 只支持 ChannelDimension.FIRST。为与慢速处理器兼容而添加。
  • input_data_format (str | ~image_utils.ChannelDimension | None.input_data_format) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "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]) — 用于处理图像的设备。如果未设置,则从输入图像推断设备。
  • return_tensors (Annotated[str | ~utils.generic.TensorType | None, None]) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。
  • disable_grouping (bool | None.disable_grouping) — 是否禁用按大小对图像进行分组,以便单独处理而非批处理。如果为 None,则当图像在 CPU 上时设置为 True,否则设置为 False。此选择基于经验观察,如下所述:https://github.com/huggingface/transformers/pull/38157
  • image_seq_length (int | None.image_seq_length) — 用于每个图像的图像 token 数量。为向后兼容而添加,但应在未来模型中设置为处理器属性。
  • do_grayscale (bool, optional, defaults to True) — 是否将图像转换为灰度。可以通过 preprocess 方法中的 do_grayscale 覆盖。

返回

<class 'transformers.image_processing_base.BatchFeature'>

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

post_process_keypoint_matching

< >

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

参数

  • outputs (LightGlueKeypointMatchingOutput) — 模型的原始输出。
  • target_sizes (torch.Tensor or list[tuple[tuple[int, int]]], optional) — 形状为 (batch_size, 2, 2) 的张量或形状为 (height, width) 的目标大小元组列表(tuple[int, int])。这必须是原始图像大小(在任何处理之前)。
  • threshold (float, optional, defaults to 0.0) — 用于过滤低分匹配的阈值。

返回

list[Dict]

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

LightGlueKeypointMatchingOutput 的原始输出转换为以原始图像尺寸为绝对坐标的关键点、得分和描述符列表。

visualize_keypoint_matching

< >

( images keypoint_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 图像列表,每个图像包含并排的图像对,以及检测到的关键点和它们之间的匹配。

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

LightGlueForKeypointMatching

class transformers.LightGlueForKeypointMatching

< >

( config: LightGlueConfig )

参数

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

LightGlue 模型,接收图像作为输入并输出它们的匹配结果。

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

此模型也是一个 PyTorch torch.nn.Module 子类。像普通的 PyTorch Module 一样使用它,并参考 PyTorch 文档了解一般用法和行为的所有相关信息。

forward

< >

( pixel_values: FloatTensor labels: torch.LongTensor | None = None output_attentions: bool | None = None output_hidden_states: bool | None = None **kwargs )

参数

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

LightGlueForKeypointMatching 的前向方法,覆盖 __call__ 特殊方法。

虽然 forward pass 的实现需要在此函数中定义,但你应该在之后调用 Module 实例而不是这个,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。

在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.